Spaces:
Running
Running
Dipti Dhawade commited on
Commit ·
17f4503
1
Parent(s): b2c44ca
Study AI integration
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +24 -2
- .github/workflows/deploy.yml +0 -52
- .gitignore +0 -48
- DEPLOYMENT.md +254 -6
- Dockerfile +33 -7
- README.md +386 -193
- backend/alerts.py +39 -0
- backend/api.py +66 -1165
- backend/auth.py +55 -9
- backend/chat_cache.py +68 -0
- backend/chroma_store.py +474 -191
- backend/deps.py +18 -0
- backend/extract_api.py +3 -73
- backend/feedback.py +45 -0
- backend/file_meta.py +45 -77
- backend/ingest_api.py +95 -119
- backend/legacy_migration.py +86 -0
- backend/library.py +766 -0
- backend/llm_pipeline.py +191 -175
- backend/mailer.py +47 -0
- backend/onenote_sync.py +11 -5
- backend/pages.py +95 -0
- backend/paths.py +110 -0
- backend/preferences.py +73 -0
- backend/rate_limit.py +99 -0
- backend/reminders.py +82 -0
- backend/routes/__init__.py +1 -0
- backend/routes/account.py +279 -0
- backend/routes/admin.py +109 -0
- backend/routes/chat.py +233 -0
- backend/routes/files.py +329 -0
- backend/routes/library.py +45 -0
- backend/routes/onenote.py +85 -0
- backend/routes/study.py +386 -0
- backend/search.py +209 -0
- backend/settings.py +135 -0
- backend/starter_notes.py +83 -0
- backend/study_store.py +328 -0
- backend/uploads.py +243 -0
- backend/usage.py +141 -0
- backend/vfs_tree.py +1 -0
- docker-compose.yml +0 -43
- frontend/my-app/.dockerignore +0 -11
- frontend/my-app/.gitignore +0 -24
- frontend/my-app/Dockerfile +0 -22
- frontend/my-app/eslint.config.js +0 -29
- frontend/my-app/index.html +0 -12
- frontend/my-app/package.json +0 -29
- frontend/my-app/src/App.jsx +0 -67
- frontend/my-app/src/auth.js +0 -100
.dockerignore
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
node_modules
|
| 2 |
dist
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
*.log
|
| 4 |
-
.
|
| 5 |
-
.git
|
|
|
|
| 1 |
+
# Only backend/, requirements.txt and the Dockerfile are needed to build the backend image.
|
| 2 |
+
.git
|
| 3 |
+
.github
|
| 4 |
+
.gitattributes
|
| 5 |
+
.vscode
|
| 6 |
+
.idea
|
| 7 |
+
.DS_Store
|
| 8 |
+
.env
|
| 9 |
+
.env.*
|
| 10 |
+
venv/
|
| 11 |
+
.venv/
|
| 12 |
+
frontend/
|
| 13 |
node_modules
|
| 14 |
dist
|
| 15 |
+
tests/
|
| 16 |
+
**/__pycache__
|
| 17 |
+
*.pyc
|
| 18 |
+
*.pyo
|
| 19 |
+
.pytest_cache/
|
| 20 |
+
.mypy_cache/
|
| 21 |
+
.ruff_cache/
|
| 22 |
+
.coverage
|
| 23 |
+
htmlcov/
|
| 24 |
+
chroma_storage/
|
| 25 |
+
user_notes/
|
| 26 |
*.log
|
| 27 |
+
*.md
|
|
|
.github/workflows/deploy.yml
DELETED
|
@@ -1,52 +0,0 @@
|
|
| 1 |
-
name: Deploy to GitHub Pages
|
| 2 |
-
|
| 3 |
-
on:
|
| 4 |
-
push:
|
| 5 |
-
branches: [main]
|
| 6 |
-
|
| 7 |
-
permissions:
|
| 8 |
-
contents: read
|
| 9 |
-
pages: write
|
| 10 |
-
id-token: write
|
| 11 |
-
|
| 12 |
-
concurrency:
|
| 13 |
-
group: "pages"
|
| 14 |
-
cancel-in-progress: false
|
| 15 |
-
|
| 16 |
-
jobs:
|
| 17 |
-
build-and-deploy:
|
| 18 |
-
runs-on: ubuntu-latest
|
| 19 |
-
environment: github-pages
|
| 20 |
-
steps:
|
| 21 |
-
- name: Checkout
|
| 22 |
-
uses: actions/checkout@v4
|
| 23 |
-
|
| 24 |
-
- name: Setup Node
|
| 25 |
-
uses: actions/setup-node@v4
|
| 26 |
-
with:
|
| 27 |
-
node-version: "20"
|
| 28 |
-
|
| 29 |
-
- name: Install and build
|
| 30 |
-
working-directory: frontend/my-app
|
| 31 |
-
env:
|
| 32 |
-
VITE_API_URL: ${{ secrets.VITE_API_URL }}
|
| 33 |
-
run: |
|
| 34 |
-
if [ -z "$VITE_API_URL" ]; then
|
| 35 |
-
echo "VITE_API_URL secret is missing. Add your backend URL (e.g. https://diptidhawade-NoteScanner.hf.space)." >&2
|
| 36 |
-
exit 1
|
| 37 |
-
fi
|
| 38 |
-
npm ci
|
| 39 |
-
npm run build
|
| 40 |
-
|
| 41 |
-
- name: Upload artifact
|
| 42 |
-
uses: actions/upload-pages-artifact@v3
|
| 43 |
-
with:
|
| 44 |
-
path: frontend/my-app/dist
|
| 45 |
-
|
| 46 |
-
deploy:
|
| 47 |
-
runs-on: ubuntu-latest
|
| 48 |
-
needs: build-and-deploy
|
| 49 |
-
environment: github-pages
|
| 50 |
-
steps:
|
| 51 |
-
- name: Deploy to GitHub Pages
|
| 52 |
-
uses: actions/deploy-pages@v4
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.gitignore
DELETED
|
@@ -1,48 +0,0 @@
|
|
| 1 |
-
# Python
|
| 2 |
-
__pycache__/
|
| 3 |
-
*.pyc
|
| 4 |
-
*.pyo
|
| 5 |
-
*.pyd
|
| 6 |
-
|
| 7 |
-
# Virtual Environments
|
| 8 |
-
venv/
|
| 9 |
-
.venv/
|
| 10 |
-
|
| 11 |
-
# ChromaDB (legacy local storage; app uses Docker Chroma server)
|
| 12 |
-
chroma_storage/
|
| 13 |
-
|
| 14 |
-
# User data
|
| 15 |
-
user_notes/
|
| 16 |
-
|
| 17 |
-
# Node
|
| 18 |
-
node_modules/
|
| 19 |
-
package-lock.json
|
| 20 |
-
|
| 21 |
-
# System/Editor
|
| 22 |
-
.DS_Store
|
| 23 |
-
Thumbs.db
|
| 24 |
-
.vscode/
|
| 25 |
-
.idea/
|
| 26 |
-
.env
|
| 27 |
-
|
| 28 |
-
# Machine Learning binaries
|
| 29 |
-
*.pth
|
| 30 |
-
*.pt
|
| 31 |
-
*.h5
|
| 32 |
-
*.ckpt
|
| 33 |
-
*.joblib
|
| 34 |
-
*.pkl
|
| 35 |
-
*.npy
|
| 36 |
-
*.npz
|
| 37 |
-
*.dylib
|
| 38 |
-
*.so
|
| 39 |
-
*.onnx
|
| 40 |
-
|
| 41 |
-
# Logs
|
| 42 |
-
*.log
|
| 43 |
-
|
| 44 |
-
# ML output folders
|
| 45 |
-
runs/
|
| 46 |
-
output/
|
| 47 |
-
checkpoints/
|
| 48 |
-
*.tensorboard/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
DEPLOYMENT.md
CHANGED
|
@@ -8,9 +8,47 @@ This project is set up for:
|
|
| 8 |
## 1) Deploy backend (Hugging Face Space)
|
| 9 |
|
| 10 |
1. Open your Space: `diptidhawade/NoteScanner`.
|
| 11 |
-
2.
|
| 12 |
-
3.
|
| 13 |
-
4.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
### Required Space secrets
|
| 16 |
|
|
@@ -24,6 +62,46 @@ This project is set up for:
|
|
| 24 |
- `SARVAM_DOC_INTEL_LANGUAGE` (optional)
|
| 25 |
- `SARVAM_DOC_INTEL_TIMEOUT` (optional)
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
### Chroma (required for persistent note features)
|
| 28 |
|
| 29 |
Use one option:
|
|
@@ -39,6 +117,7 @@ Use one option:
|
|
| 39 |
|
| 40 |
1. Wait for Space build to finish.
|
| 41 |
2. Copy backend URL, e.g. `https://diptidhawade-NoteScanner.hf.space`
|
|
|
|
| 42 |
|
| 43 |
## 2) Configure GitHub Pages frontend
|
| 44 |
|
|
@@ -51,7 +130,17 @@ Use one option:
|
|
| 51 |
2. GitHub Pages URL will be:
|
| 52 |
- `https://<your-username>.github.io/NoteScanner/`
|
| 53 |
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
1. Open frontend URL.
|
| 57 |
2. Confirm these work:
|
|
@@ -60,7 +149,166 @@ Use one option:
|
|
| 60 |
- explorer upload
|
| 61 |
- study generation
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
## Notes
|
| 64 |
|
| 65 |
-
- Backend on free HF Space may sleep when idle (cold start delay on first request).
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
## 1) Deploy backend (Hugging Face Space)
|
| 9 |
|
| 10 |
1. Open your Space: `diptidhawade/NoteScanner`.
|
| 11 |
+
2. Ensure the Space uses the root `Dockerfile` (already configured to run on `${PORT}` with default `7860`).
|
| 12 |
+
3. In Space **Settings -> Variables and secrets**, add the settings below.
|
| 13 |
+
4. Deploy the code, either automatically (recommended) or by hand:
|
| 14 |
+
|
| 15 |
+
### Automatic backend deploy (GitHub Actions)
|
| 16 |
+
|
| 17 |
+
The workflow `.github/workflows/deploy-backend.yml` pushes the backend to the Space on every push to `main`
|
| 18 |
+
(or when you run it by hand from the **Actions** tab).
|
| 19 |
+
|
| 20 |
+
1. On Hugging Face, create a **write** access token: **Settings -> Access Tokens -> New token** (type: Write).
|
| 21 |
+
2. In your GitHub repo, go to **Settings -> Secrets and variables -> Actions -> New repository secret** and add:
|
| 22 |
+
- `HF_TOKEN` = that token
|
| 23 |
+
3. Push to `main`. Without `HF_TOKEN` the workflow skips the deploy and shows a notice instead of failing.
|
| 24 |
+
|
| 25 |
+
What it sends to the Space: `backend/`, `Dockerfile`, `.dockerignore`, `requirements.txt`, `DEPLOYMENT.md` and
|
| 26 |
+
`README.md`. The frontend isn't needed there (it lives on GitHub Pages), and no binary files are sent
|
| 27 |
+
(Spaces reject them unless they use Git LFS).
|
| 28 |
+
|
| 29 |
+
### Space README front matter
|
| 30 |
+
|
| 31 |
+
Hugging Face reads the Space's settings from YAML at the very top of its `README.md`:
|
| 32 |
+
|
| 33 |
+
```yaml
|
| 34 |
+
---
|
| 35 |
+
title: NoteScanner
|
| 36 |
+
emoji: "📚"
|
| 37 |
+
colorFrom: indigo
|
| 38 |
+
colorTo: blue
|
| 39 |
+
sdk: docker
|
| 40 |
+
app_port: 7860
|
| 41 |
+
pinned: false
|
| 42 |
+
---
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
The GitHub `README.md` doesn't carry this block. The deploy workflow adds it to the Space's copy
|
| 46 |
+
automatically. If you upload files to the Space by hand, keep this block at the top of the Space's `README.md`.
|
| 47 |
+
|
| 48 |
+
### Manual deploy (only if you don't use the workflow)
|
| 49 |
+
|
| 50 |
+
In the Space's **Files** tab, upload the same files the workflow sends (`backend/`, `Dockerfile`,
|
| 51 |
+
`.dockerignore`, `requirements.txt`, and `README.md` with the front matter above).
|
| 52 |
|
| 53 |
### Required Space secrets
|
| 54 |
|
|
|
|
| 62 |
- `SARVAM_DOC_INTEL_LANGUAGE` (optional)
|
| 63 |
- `SARVAM_DOC_INTEL_TIMEOUT` (optional)
|
| 64 |
|
| 65 |
+
### Security settings
|
| 66 |
+
|
| 67 |
+
- `CORS_ORIGINS` (only needed if your frontend is not at `https://cherie-dips.github.io`):
|
| 68 |
+
the website(s) allowed to call the backend, comma-separated, e.g. `https://<your-username>.github.io`
|
| 69 |
+
- Optional: `SESSION_TTL_DAYS`, `MAX_UPLOAD_MB`, `MAX_CHAT_UPLOAD_CHARS`, `CHAT_CACHE_TTL_SECONDS`
|
| 70 |
+
- Request limits (overall per address/browser, logins, uploads, questions, study tools, daily AI caps)
|
| 71 |
+
are the `LIMIT_*` values in `backend/settings.py`; see "Request limits" in the README. To loosen or
|
| 72 |
+
tighten all of them without a code change, set `RATE_LIMIT_MULTIPLIER` (e.g. `2` doubles every limit).
|
| 73 |
+
|
| 74 |
+
### Password-reset emails (optional)
|
| 75 |
+
|
| 76 |
+
"Forgot password" emails are only turned on when both `SMTP_HOST` and `SMTP_FROM` are set.
|
| 77 |
+
Without them, the app explains that password reset by email isn't available.
|
| 78 |
+
|
| 79 |
+
- `FRONTEND_URL`: the address people open the app at, used to build the reset link,
|
| 80 |
+
e.g. `https://cherie-dips.github.io/NoteScanner/`
|
| 81 |
+
- `SMTP_HOST`: your email provider's SMTP server, e.g. `smtp.gmail.com`
|
| 82 |
+
- `SMTP_PORT`: usually `587`
|
| 83 |
+
- `SMTP_USERNAME` and `SMTP_PASSWORD`: the login for that server (for Gmail, an app password)
|
| 84 |
+
- `SMTP_FROM`: the sender address shown to users, e.g. `NoteScanner <noreply@example.com>`
|
| 85 |
+
- `SMTP_STARTTLS`: `true` (default) for port 587
|
| 86 |
+
|
| 87 |
+
The same email settings send **daily review reminders** to students who turn them on in Account
|
| 88 |
+
settings: `REMINDER_HOUR` (default `8`, in `APP_TIMEZONE`, default `Asia/Kolkata`) is the hour after
|
| 89 |
+
which the day's emails go out; `REMINDERS_ENABLED=false` turns the feature off.
|
| 90 |
+
|
| 91 |
+
### Running a pilot (optional settings)
|
| 92 |
+
|
| 93 |
+
- `ADMIN_EMAILS`: comma-separated emails that can open "Usage & feedback" in the profile menu
|
| 94 |
+
(active students, questions, uploads, pages read, reviews, ratings, feedback, estimated cost).
|
| 95 |
+
- `ALERT_WEBHOOK_URL`: a Slack or Discord incoming-webhook address. Server crashes, failed uploads,
|
| 96 |
+
AI outages and failed reminder emails are posted there (each kind at most once per 10 minutes).
|
| 97 |
+
- AI cost estimate: `AI_PRICE_PER_PAGE` (Sarvam Vision, per page), `AI_PRICE_PER_1K_INPUT_TOKENS`,
|
| 98 |
+
`AI_PRICE_PER_1K_OUTPUT_TOKENS` and `AI_PRICE_CURRENCY` (default `INR`). Copy the prices from
|
| 99 |
+
your Sarvam plan; until they're set the admin page shows usage counts but no cost.
|
| 100 |
+
- `AI_MONTHLY_BUDGET`: once this month's estimated cost reaches it, reading files, answers and study
|
| 101 |
+
tools pause until next month (notes and flashcard reviews keep working). `0` (default) = no limit.
|
| 102 |
+
Needs the prices above.
|
| 103 |
+
- `STARTER_NOTES=false`: don't give new accounts the "Getting started" folder.
|
| 104 |
+
|
| 105 |
### Chroma (required for persistent note features)
|
| 106 |
|
| 107 |
Use one option:
|
|
|
|
| 117 |
|
| 118 |
1. Wait for Space build to finish.
|
| 119 |
2. Copy backend URL, e.g. `https://diptidhawade-NoteScanner.hf.space`
|
| 120 |
+
3. Check it's up: open `https://diptidhawade-NoteScanner.hf.space/health` (should show `{"status":"ok"}`).
|
| 121 |
|
| 122 |
## 2) Configure GitHub Pages frontend
|
| 123 |
|
|
|
|
| 130 |
2. GitHub Pages URL will be:
|
| 131 |
- `https://<your-username>.github.io/NoteScanner/`
|
| 132 |
|
| 133 |
+
The Pages workflow installs exact versions from `frontend/my-app/package-lock.json` (`npm ci`) and runs the
|
| 134 |
+
code checker (ESLint) before building, so commit the lockfile whenever you add or update packages.
|
| 135 |
+
|
| 136 |
+
## 3) Checks on every push (CI)
|
| 137 |
+
|
| 138 |
+
`.github/workflows/ci.yml` runs on every push to `main` and on pull requests:
|
| 139 |
+
|
| 140 |
+
- Backend: installs the pinned packages and runs the tests in `tests/` (no AI service or database needed).
|
| 141 |
+
- Frontend: runs ESLint and a production build.
|
| 142 |
+
|
| 143 |
+
## 4) Verify
|
| 144 |
|
| 145 |
1. Open frontend URL.
|
| 146 |
2. Confirm these work:
|
|
|
|
| 149 |
- explorer upload
|
| 150 |
- study generation
|
| 151 |
|
| 152 |
+
## 5) Shared course library and SDE-Prep (Study AI + Ask AI)
|
| 153 |
+
|
| 154 |
+
[SDE-Prep](https://cherie-dips.github.io/SDE-Prep/) uses this backend in two ways:
|
| 155 |
+
|
| 156 |
+
- **Study AI tab**: this frontend inside SDE-Prep (`/NoteScanner/?embed=sde`), in SDE-Prep's colours.
|
| 157 |
+
Both sites are on `cherie-dips.github.io`, so they share the sign-in.
|
| 158 |
+
- **Ask AI** in SDE-Prep's Notes tab: questions, flashcards, quizzes and summaries about the course PDFs
|
| 159 |
+
shown there. Those PDFs are read **once** on the server into the shared course library
|
| 160 |
+
(`backend/library.py`) and searched by every student; nothing is copied per student.
|
| 161 |
+
|
| 162 |
+
`https://cherie-dips.github.io` is already allowed by the default `CORS_ORIGINS`.
|
| 163 |
+
|
| 164 |
+
### Index the course PDFs (once)
|
| 165 |
+
|
| 166 |
+
From your computer, with `.env` pointing at Chroma Cloud and holding `SARVAM_API_KEY`:
|
| 167 |
+
|
| 168 |
+
```bash
|
| 169 |
+
python scripts/index_library.py --dry-run # lists the PDFs and how many pieces need OCR, and the cost
|
| 170 |
+
python scripts/index_library.py # reads and indexes them
|
| 171 |
+
```
|
| 172 |
+
|
| 173 |
+
Handwritten and scanned pages are read with Sarvam Vision (≈ ₹0.5 per piece at Sarvam's listed price;
|
| 174 |
+
`--dry-run` prints the total first). Typed pages are read for free. Without a Sarvam key the script uses
|
| 175 |
+
Tesseract instead (free, much weaker on handwriting). Running it again only reads new or changed PDFs.
|
| 176 |
+
|
| 177 |
+
Or from the server, as an admin (`ADMIN_EMAILS`): `POST /admin/library/sync` starts a sync in the
|
| 178 |
+
background, and `GET /admin/library` shows each PDF's status.
|
| 179 |
+
|
| 180 |
+
### Keep it up to date
|
| 181 |
+
|
| 182 |
+
- After adding PDFs to the Supabase bucket, run the script again (or the admin sync), or
|
| 183 |
+
- set `LIBRARY_SYNC_HOURS` (e.g. `24`) on the Space to check the bucket automatically.
|
| 184 |
+
|
| 185 |
+
Library OCR counts towards `AI_MONTHLY_BUDGET`; when the budget is used up, PDFs that need OCR wait for
|
| 186 |
+
the next sync (typed PDFs are still indexed).
|
| 187 |
+
|
| 188 |
+
### Settings (all optional)
|
| 189 |
+
|
| 190 |
+
| Setting | Default | What it does |
|
| 191 |
+
|---|---|---|
|
| 192 |
+
| `LIBRARY_ENABLED` | `true` | Turn the shared library (and Ask AI's course search) on or off |
|
| 193 |
+
| `LIBRARY_SUPABASE_URL`, `LIBRARY_SUPABASE_KEY`, `LIBRARY_BUCKET` | SDE-Prep's bucket | Where the PDFs are (the key is the public, read-only anon key) |
|
| 194 |
+
| `LIBRARY_PREFIXES` | `plaksha-university` | Bucket folders to index (comma-separated) |
|
| 195 |
+
| `LIBRARY_OCR` | `auto` | `auto` (Sarvam if a key is set, else Tesseract), `sarvam`, `tesseract` or `off` |
|
| 196 |
+
| `LIBRARY_SYNC_HOURS` | `0` | Re-check the bucket every N hours (`0` = only when started by hand) |
|
| 197 |
+
|
| 198 |
+
### Verify
|
| 199 |
+
|
| 200 |
+
1. `GET /library/status` lists the indexed PDFs.
|
| 201 |
+
2. In SDE-Prep, open Notes → a course PDF → **Ask AI**: sign in, ask a question, click a source
|
| 202 |
+
(the PDF scrolls to that spot).
|
| 203 |
+
3. Open the **Study AI** tab: you are already signed in, and a deck saved from Ask AI is under Review.
|
| 204 |
+
|
| 205 |
## Notes
|
| 206 |
|
| 207 |
+
- Backend on free HF Space may sleep when idle (cold start delay on first request). The search model is
|
| 208 |
+
downloaded while the image is built, so waking up doesn't download it again.
|
| 209 |
+
- The backend must run as a single process (one uvicorn worker, as the `Dockerfile` does): the chat-upload
|
| 210 |
+
cache, request limits and per-user locks live in that process's memory.
|
| 211 |
+
- If frontend shows backend/network errors, first check `VITE_API_URL` secret and Space build logs.
|
| 212 |
+
- If the browser console shows a CORS error, add your frontend's address to `CORS_ORIGINS`.
|
| 213 |
+
- After this update everyone has to sign in once more (older logins had no expiry date and are now treated as expired).
|
| 214 |
+
|
| 215 |
+
## Local development with Docker Compose
|
| 216 |
+
|
| 217 |
+
`docker compose up --build` starts a local Chroma server, the backend on `http://localhost:8000` and the
|
| 218 |
+
frontend dev server on `http://localhost:5173`. Local Chroma data is kept in the `chroma_data` volume
|
| 219 |
+
(mounted at `/data`, where Chroma 1.x stores it).
|
| 220 |
+
|
| 221 |
+
## Backups and restore
|
| 222 |
+
|
| 223 |
+
Chroma Cloud holds the only copy of every student's account, notes, folders and flashcard decks.
|
| 224 |
+
Regular backups, and checking that they can be restored, are how this project protects against
|
| 225 |
+
losing that data (a bad deploy, an accidental delete, or a problem with the Chroma account).
|
| 226 |
+
|
| 227 |
+
### Weekly automatic backup
|
| 228 |
+
|
| 229 |
+
`.github/workflows/backup.yml` runs every Sunday at 03:00 India time (and on demand from the
|
| 230 |
+
Actions tab → "Weekly backup" → Run workflow). Add these repository secrets (Settings → Secrets and
|
| 231 |
+
variables → Actions → Secrets):
|
| 232 |
+
|
| 233 |
+
- `CHROMA_API_KEY`, `CHROMA_TENANT`, `CHROMA_DATABASE`: the same values as on the Space.
|
| 234 |
+
- `BACKUP_PASSPHRASE`: a long random passphrase. **Store it somewhere safe outside GitHub** (a
|
| 235 |
+
password manager): without it the backups can't be opened.
|
| 236 |
+
|
| 237 |
+
Until all four are set, the workflow skips with a notice. Each run saves one encrypted file as a
|
| 238 |
+
workflow artifact (kept 90 days). The backup holds password hashes and students' notes, so it's
|
| 239 |
+
encrypted before upload: artifacts of a public repository can be downloaded by others.
|
| 240 |
+
|
| 241 |
+
### Back up by hand
|
| 242 |
+
|
| 243 |
+
```bash
|
| 244 |
+
python scripts/backup_chroma.py # writes notescanner-backup-<UTC time>.jsonl.gz
|
| 245 |
+
python scripts/backup_chroma.py --out my-backup.jsonl.gz
|
| 246 |
+
```
|
| 247 |
+
|
| 248 |
+
It reads the Chroma settings from `.env` (or the environment). Login sessions, password-reset links
|
| 249 |
+
and OneNote sign-in tokens are left out on purpose: after a restore, students sign in again and
|
| 250 |
+
reconnect OneNote. Keep backup files private.
|
| 251 |
+
|
| 252 |
+
### Open an encrypted backup
|
| 253 |
+
|
| 254 |
+
Download the artifact from the workflow run (it's a zip containing the `.gpg` file), then:
|
| 255 |
+
|
| 256 |
+
```bash
|
| 257 |
+
gpg --decrypt notescanner-backup-<time>.jsonl.gz.gpg > notescanner-backup.jsonl.gz
|
| 258 |
+
```
|
| 259 |
+
|
| 260 |
+
(gpg asks for `BACKUP_PASSPHRASE`.)
|
| 261 |
+
|
| 262 |
+
### Restore
|
| 263 |
+
|
| 264 |
+
```bash
|
| 265 |
+
python scripts/restore_chroma.py notescanner-backup.jsonl.gz --dry-run # check the file, change nothing
|
| 266 |
+
python scripts/restore_chroma.py notescanner-backup.jsonl.gz
|
| 267 |
+
```
|
| 268 |
+
|
| 269 |
+
It restores into the database configured in `.env`. It refuses to write into collections that
|
| 270 |
+
already have records, so it can't mix old data into live data by accident; `--force` writes anyway
|
| 271 |
+
(records with the same id are replaced, others are kept). It also refuses a backup file that was cut
|
| 272 |
+
off before it finished.
|
| 273 |
+
|
| 274 |
+
### Test a restore (do this at least once, and after big changes)
|
| 275 |
+
|
| 276 |
+
A backup you have never restored isn't proof you can recover. To test without touching live data:
|
| 277 |
+
|
| 278 |
+
1. Create a second, empty database in Chroma Cloud (e.g. `notescanner-restore-test`).
|
| 279 |
+
2. Restore into it by pointing the settings at that database for one command:
|
| 280 |
+
`CHROMA_DATABASE=notescanner-restore-test python scripts/restore_chroma.py notescanner-backup.jsonl.gz`
|
| 281 |
+
(environment variables you set like this take priority over `.env`).
|
| 282 |
+
3. Run the backend locally against that database the same way
|
| 283 |
+
(`CHROMA_DATABASE=notescanner-restore-test uvicorn backend.api:app --port 8000`) and check you can
|
| 284 |
+
sign in, see your folders and files, ask a question and review a deck.
|
| 285 |
+
4. Delete the test database afterwards.
|
| 286 |
+
|
| 287 |
+
## Uptime check
|
| 288 |
+
|
| 289 |
+
`.github/workflows/uptime.yml` calls `<backend>/health` every 15 minutes and fails if it doesn't
|
| 290 |
+
answer `{"status":"ok"}` within 30 seconds. GitHub emails a failed run to the person who last changed
|
| 291 |
+
the workflow's schedule. To turn it on, add the repository variable `BACKEND_URL` (Settings → Secrets
|
| 292 |
+
and variables → Actions → Variables), e.g. `https://diptidhawade-NoteScanner.hf.space`.
|
| 293 |
+
|
| 294 |
+
- A free Space that has gone to sleep can take longer than 30 seconds to wake up, so expect a failure
|
| 295 |
+
now and then until the backend is on always-on hosting. The regular checks also keep a free Space awake.
|
| 296 |
+
- GitHub pauses scheduled workflows in repositories with no activity for 60 days; re-enable it from the
|
| 297 |
+
Actions tab if that happens.
|
| 298 |
+
|
| 299 |
+
## Answer-quality test
|
| 300 |
+
|
| 301 |
+
`scripts/answer_quality.py` signs in to a running backend, asks a fixed list of questions and scores
|
| 302 |
+
whether each answer contains the key points it should (0–100 overall). Run it before and after
|
| 303 |
+
changing the AI prompts, the AI model or the search settings, and compare the two runs:
|
| 304 |
+
|
| 305 |
+
```bash
|
| 306 |
+
export NOTESCANNER_PASSWORD='test account password'
|
| 307 |
+
python scripts/answer_quality.py --api https://diptidhawade-NoteScanner.hf.space \
|
| 308 |
+
--email answer-test@example.com --questions evals/sample_questions.json \
|
| 309 |
+
--baseline evals/results/<earlier run>.json --min-score 70 --max-drop 5
|
| 310 |
+
```
|
| 311 |
+
|
| 312 |
+
Use a separate test account. `evals/sample_questions.json` works with the "Getting started" notes every
|
| 313 |
+
new account receives; write about 30 questions from a real course's notes as described in
|
| 314 |
+
`evals/README.md`. Results are saved in `evals/results/`.
|
Dockerfile
CHANGED
|
@@ -1,15 +1,41 @@
|
|
| 1 |
-
FROM python:3.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
WORKDIR /app
|
| 4 |
|
| 5 |
-
|
|
|
|
| 6 |
|
| 7 |
COPY requirements.txt .
|
| 8 |
-
RUN pip install -
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
|
| 15 |
-
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
ENV PYTHONUNBUFFERED=1 \
|
| 4 |
+
PYTHONDONTWRITEBYTECODE=1 \
|
| 5 |
+
PIP_NO_CACHE_DIR=1 \
|
| 6 |
+
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
| 7 |
+
HF_HOME=/opt/hf-cache \
|
| 8 |
+
PORT=7860
|
| 9 |
+
|
| 10 |
+
RUN apt-get update \
|
| 11 |
+
&& apt-get install -y --no-install-recommends tesseract-ocr \
|
| 12 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 13 |
+
|
| 14 |
+
# Hugging Face Spaces run containers as uid 1000.
|
| 15 |
+
RUN useradd --create-home --uid 1000 user
|
| 16 |
|
| 17 |
WORKDIR /app
|
| 18 |
|
| 19 |
+
# CPU-only torch first: the default wheel bundles ~2 GB of GPU libraries the server can't use.
|
| 20 |
+
RUN pip install --index-url https://download.pytorch.org/whl/cpu torch==2.8.0
|
| 21 |
|
| 22 |
COPY requirements.txt .
|
| 23 |
+
RUN pip install -r requirements.txt
|
| 24 |
+
|
| 25 |
+
# Download the embedding model during the build so the first request after a restart is fast.
|
| 26 |
+
RUN mkdir -p "$HF_HOME" \
|
| 27 |
+
&& python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('all-MiniLM-L6-v2')" \
|
| 28 |
+
&& chown -R user:user "$HF_HOME"
|
| 29 |
+
ENV HF_HUB_OFFLINE=1
|
| 30 |
+
|
| 31 |
+
COPY --chown=user:user backend ./backend
|
| 32 |
+
|
| 33 |
+
USER user
|
| 34 |
|
| 35 |
+
EXPOSE 7860
|
| 36 |
|
| 37 |
+
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
|
| 38 |
+
CMD python -c "import os, urllib.request; urllib.request.urlopen('http://127.0.0.1:%s/health' % os.environ.get('PORT', '7860'), timeout=4)" || exit 1
|
| 39 |
|
| 40 |
+
# One worker: the chat-upload cache, request limits and per-user locks live in process memory.
|
| 41 |
+
CMD ["sh", "-c", "exec uvicorn backend.api:app --host 0.0.0.0 --port ${PORT:-7860} --workers 1"]
|
README.md
CHANGED
|
@@ -4,265 +4,458 @@ emoji: "📚"
|
|
| 4 |
colorFrom: indigo
|
| 5 |
colorTo: blue
|
| 6 |
sdk: docker
|
|
|
|
| 7 |
pinned: false
|
| 8 |
---
|
| 9 |
|
| 10 |
# NoteScanner
|
| 11 |
|
| 12 |
-
|
| 13 |
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
-
|
| 17 |
-
- Store persistent note chunks + embeddings in ChromaDB for retrieval.
|
| 18 |
-
- Support temporary chat-only uploads from the chatbot `+` button (ephemeral cache, no DB persistence).
|
| 19 |
-
- Answer questions and generate flashcards/MCQs/mind maps from retrieved context.
|
| 20 |
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
NoteScanner Demo
|
| 26 |
-
|
| 27 |
-
## Prerequisites
|
| 28 |
-
|
| 29 |
-
- Docker & Docker Compose
|
| 30 |
-
- Python 3.10+
|
| 31 |
-
- Node.js 20+
|
| 32 |
-
|
| 33 |
-
## System Architecture
|
| 34 |
-
|
| 35 |
-
- `frontend/my-app`: React + Vite UI
|
| 36 |
-
- `backend/api.py`: FastAPI API layer
|
| 37 |
-
- `backend/chroma_store.py`: Chroma client + collection accessors
|
| 38 |
-
- `backend/ingest_api.py`: chunking + embedding ingestion
|
| 39 |
-
- `backend/llm_pipeline.py`: OCR + LLM calls
|
| 40 |
-
- `backend/vfs_tree.py`: virtual folder tree helpers
|
| 41 |
-
- `backend/file_meta.py`: file metadata policy layer
|
| 42 |
-
|
| 43 |
-
## End-to-End Pipeline
|
| 44 |
-
|
| 45 |
-
### 1) Persistent note upload pipeline (Explorer)
|
| 46 |
-
|
| 47 |
-
Endpoint: `POST /upload_note`
|
| 48 |
-
|
| 49 |
-
Flow:
|
| 50 |
-
|
| 51 |
-
1. Client uploads file to backend.
|
| 52 |
-
2. Backend reads file bytes in memory.
|
| 53 |
-
3. Text extraction:
|
| 54 |
-
- PDF: Sarvam Document Intelligence first, parser fallback.
|
| 55 |
-
- Image: Sarvam Vision OCR first, Tesseract fallback.
|
| 56 |
-
- Plain text formats: UTF-8 decode.
|
| 57 |
-
4. Backend persists:
|
| 58 |
-
- full extracted text in `user_documents`,
|
| 59 |
-
- chunked text + embeddings in `user_{user_id}_notes`.
|
| 60 |
-
5. VFS is updated for explorer visibility.
|
| 61 |
-
|
| 62 |
-
### 2) Ephemeral chatbot `+` upload pipeline
|
| 63 |
-
|
| 64 |
-
Endpoint: `POST /chat/upload_ephemeral`
|
| 65 |
-
|
| 66 |
-
Flow:
|
| 67 |
-
|
| 68 |
-
1. Frontend sends file with `chat_session_id`.
|
| 69 |
-
2. Backend extracts text in memory.
|
| 70 |
-
3. Backend stores extracted text in process memory cache keyed by `(user_id, chat_session_id)`.
|
| 71 |
-
|
| 72 |
-
Important:
|
| 73 |
-
|
| 74 |
-
- No `user_documents` write.
|
| 75 |
-
- No `user_{user_id}_notes` write.
|
| 76 |
-
- No Chroma persistence for this path.
|
| 77 |
-
|
| 78 |
-
Cache clear:
|
| 79 |
-
|
| 80 |
-
- `POST /chat/session/clear`
|
| 81 |
-
- Triggered by chat refresh/new chat/unmount.
|
| 82 |
-
|
| 83 |
-
### 3) Query retrieval sequence (implemented priority)
|
| 84 |
-
|
| 85 |
-
Endpoint: `POST /query_folder`
|
| 86 |
-
|
| 87 |
-
Retrieval order:
|
| 88 |
-
|
| 89 |
-
1. Ephemeral chat uploads (`+` cache)
|
| 90 |
-
2. Opened file in viewer
|
| 91 |
-
3. Other files in same course folder
|
| 92 |
-
|
| 93 |
-
Selection logic:
|
| 94 |
|
| 95 |
-
|
| 96 |
-
- The highest-priority relevant stage is selected.
|
| 97 |
-
- If relevance is weak at a higher stage, system falls to next stage.
|
| 98 |
-
- This reduces unrelated-domain leakage (for example RL queries answered from generic ML notes).
|
| 99 |
|
| 100 |
-
|
| 101 |
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
-
|
| 105 |
-
- `POST /study/mindmap`
|
| 106 |
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
|
|
|
| 111 |
|
| 112 |
-
|
| 113 |
|
| 114 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
-
-
|
| 117 |
-
- `POST /login`
|
| 118 |
-
- `GET /me`
|
| 119 |
-
- `GET /guest_id`
|
| 120 |
|
| 121 |
-
##
|
| 122 |
|
| 123 |
-
|
| 124 |
-
- `POST /create_folder`
|
| 125 |
-
- `POST /create_file`
|
| 126 |
-
- `POST /upload_note`
|
| 127 |
-
- `POST /move_path`
|
| 128 |
-
- `POST /delete_path`
|
| 129 |
-
- `DELETE /notes`
|
| 130 |
-
- `GET /file_meta`
|
| 131 |
-
- `POST /file_meta`
|
| 132 |
|
| 133 |
-
###
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
-
|
| 140 |
|
| 141 |
-
|
| 142 |
-
- `POST /study/mindmap`
|
| 143 |
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
- `GET /integrations/onenote/callback`
|
| 149 |
-
- `POST /integrations/onenote/sync`
|
| 150 |
|
| 151 |
-
##
|
| 152 |
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
-
|
|
|
|
|
|
|
| 156 |
|
| 157 |
-
|
| 158 |
-
- `sessions`: session_id -> user_id
|
| 159 |
-
- `user_documents`: full extracted text per logical path
|
| 160 |
-
- `user_{user_id}_notes`: chunk docs + embeddings + chunk metadata
|
| 161 |
-
- `user_{user_id}_vfs`: virtual tree + file meta JSON
|
| 162 |
-
- `onenote_tokens`: OAuth tokens
|
| 163 |
-
- `onenote_oauth_states`: OAuth state for callback
|
| 164 |
|
| 165 |
-
Notes
|
|
|
|
| 166 |
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
-
|
|
|
|
|
|
|
| 172 |
|
| 173 |
-
|
| 174 |
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
-
|
| 179 |
-
|
| 180 |
-
-
|
| 181 |
-
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
-
|
| 185 |
|
| 186 |
-
|
| 187 |
-
- `SARVAM_MODEL_STUDY` (default: `sarvam-30b`)
|
| 188 |
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
-
|
| 192 |
|
| 193 |
-
|
| 194 |
|
| 195 |
-
|
| 196 |
|
| 197 |
-
|
| 198 |
-
- `SARVAM_MODEL_RAG`
|
| 199 |
-
- `SARVAM_MODEL_STUDY`
|
| 200 |
-
- `SARVAM_DOC_INTEL_LANGUAGE` (default `en-IN`)
|
| 201 |
-
- `SARVAM_DOC_INTEL_TIMEOUT` (default `180`)
|
| 202 |
|
| 203 |
-
|
|
|
|
| 204 |
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
- Self-hosted:
|
| 210 |
-
- `CHROMA_HOST`
|
| 211 |
-
- `CHROMA_PORT`
|
| 212 |
-
- `CHROMA_SSL` (optional)
|
| 213 |
|
| 214 |
-
|
|
|
|
|
|
|
|
|
|
| 215 |
|
| 216 |
-
|
| 217 |
-
|
| 218 |
|
| 219 |
-
##
|
| 220 |
|
| 221 |
```bash
|
| 222 |
docker compose up --build
|
| 223 |
```
|
| 224 |
|
| 225 |
-
|
|
|
|
|
|
|
| 226 |
|
| 227 |
-
|
| 228 |
-
- Frontend: `http://localhost:5173`
|
| 229 |
|
| 230 |
-
|
|
|
|
|
|
|
| 231 |
|
| 232 |
```bash
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
```
|
| 235 |
|
| 236 |
-
|
| 237 |
|
| 238 |
-
|
| 239 |
|
| 240 |
```bash
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
pip install -r requirements.txt
|
| 244 |
-
uvicorn backend.api:app --host 0.0.0.0 --port 8000
|
| 245 |
```
|
| 246 |
|
| 247 |
-
|
| 248 |
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
npm run dev -- --host
|
| 253 |
-
```
|
| 254 |
|
| 255 |
-
|
|
|
|
| 256 |
|
| 257 |
-
-
|
| 258 |
-
- Temporary uploads are not persisted in Chroma collections.
|
| 259 |
-
- Query routing order is: chat cache -> open file -> same-course files.
|
| 260 |
-
- Chat refresh/new chat clears temporary cache.
|
| 261 |
|
| 262 |
-
|
|
|
|
| 263 |
|
| 264 |
-
-
|
| 265 |
-
- `frontend/my-app/` UI and interaction layer
|
| 266 |
-
- `docker-compose.yml` local orchestration
|
| 267 |
-
- `requirements.txt` backend dependencies
|
| 268 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
colorFrom: indigo
|
| 5 |
colorTo: blue
|
| 6 |
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
pinned: false
|
| 9 |
---
|
| 10 |
|
| 11 |
# NoteScanner
|
| 12 |
|
| 13 |
+
**A study assistant that works from your own notes.**
|
| 14 |
|
| 15 |
+
Upload your course notes (PDFs, photos of handwritten pages, text files or OneNote pages). Then ask
|
| 16 |
+
questions and get answers taken from those notes, with the exact file and page they came from.
|
| 17 |
+
NoteScanner can also make flashcards and practice quizzes from your notes, remind you when cards are
|
| 18 |
+
due for review, and build a day-by-day revision plan before an exam.
|
| 19 |
|
| 20 |
+

|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
+
**Also part of [SDE-Prep](https://cherie-dips.github.io/SDE-Prep/).** There it is the **Study AI** tab
|
| 23 |
+
(this app in SDE-Prep's colours, with the same sign-in), and it powers **Ask AI** in SDE-Prep's Notes tab:
|
| 24 |
+
questions, flashcards, quizzes and summaries about the course PDFs shown there, which the server reads
|
| 25 |
+
once into a shared course library. See [The shared course library](#4-the-shared-course-library).
|
| 26 |
|
| 27 |
+
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
+
## The problem
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
When exams come close, most students run into the same problems:
|
| 32 |
|
| 33 |
+
- **Notes are scattered.** Slides from the professor, scanned handouts, phone photos of a friend's
|
| 34 |
+
notebook, a few OneNote pages. Finding one explanation means opening ten files.
|
| 35 |
+
- **Handwritten notes and scanned pages can't be searched.** Ctrl+F doesn't work on a photo.
|
| 36 |
+
- **General chatbots don't know your course.** They answer from the internet, so the method,
|
| 37 |
+
notation or definition can differ from what your class taught, and you can't easily tell which
|
| 38 |
+
parts to trust.
|
| 39 |
+
- **Making study material takes time.** Writing flashcards and practice questions by hand is slow,
|
| 40 |
+
so most students skip it and just re-read.
|
| 41 |
+
- **Cramming doesn't stick.** Reviewing a little every day works better, but it's hard to keep track
|
| 42 |
+
of what to review and when.
|
| 43 |
|
| 44 |
+
## What NoteScanner does about it
|
|
|
|
| 45 |
|
| 46 |
+
| Problem | What NoteScanner does |
|
| 47 |
+
|---|---|
|
| 48 |
+
| Notes are scattered | One place for all your notes, organised in folders (one folder per course). |
|
| 49 |
+
| Photos and scans can't be searched | Reads the text out of every PDF and photo, including handwriting, so all of it can be searched. You can view and correct that text. |
|
| 50 |
+
| Chatbots don't know your course | Answers come from **your notes first**, with clickable sources (file and page). If the notes don't fully cover a question, anything added from general knowledge is clearly marked **📖 Beyond notes**. |
|
| 51 |
+
| Making study material is slow | Makes flashcards, multiple-choice quizzes (with explanations) and short summaries from any file in one click. |
|
| 52 |
+
| Cramming doesn't stick | Saves flashcards into decks and shows each card again at the right time (cards you know come back less often). A "Today" dashboard, an exam planner, and an optional daily reminder email. |
|
| 53 |
|
| 54 |
+
It is built for students in India: answers and study material can be written in English or in one of
|
| 55 |
+
10 Indian languages (Hindi, Bengali, Gujarati, Kannada, Malayalam, Marathi, Odia, Punjabi, Tamil,
|
| 56 |
+
Telugu).
|
| 57 |
|
| 58 |
+
---
|
| 59 |
|
| 60 |
+
## Features
|
| 61 |
+
|
| 62 |
+
**Your notes**
|
| 63 |
+
- Folders and files: upload many files at once (or drag and drop), rename, move, delete.
|
| 64 |
+
- Uploads are processed in the background, with progress shown for each file.
|
| 65 |
+
- Mark a file as a **main source** (for example, the professor's official notes) so answers prefer it.
|
| 66 |
+
- **Text view**: see the text NoteScanner read from a file, fix reading mistakes, or type notes into a new file.
|
| 67 |
+
- **OneNote import** (when Microsoft sign-in is set up).
|
| 68 |
+
- Your original PDFs and photos stay on your device for viewing. The server keeps only the text read from them.
|
| 69 |
+
|
| 70 |
+
**Ask your notes**
|
| 71 |
+
- Answers appear word by word as they are written, with sources you can click (with page numbers for PDFs).
|
| 72 |
+
- Select any passage in a file and choose **Ask about this**.
|
| 73 |
+
- Attach a file to just one chat with the **+** button, without saving it to your notes.
|
| 74 |
+
- Math is shown properly (fractions, equations, symbols).
|
| 75 |
+
|
| 76 |
+
**Study tools**
|
| 77 |
+
- Flashcards and multiple-choice quizzes (with a score and explanations), made from the open file.
|
| 78 |
+
- Optional: make flashcards automatically for every upload.
|
| 79 |
+
- Short 100–150 word summaries of a file.
|
| 80 |
+
- Saved decks with spaced review (Again / Hard / Good / Easy). Export a deck as CSV for Anki.
|
| 81 |
+
- **Today** dashboard: cards due, streak, weak topics (from quiz scores), last 14 days of activity.
|
| 82 |
+
- **Exam mode**: a day-by-day revision plan up to an exam date, and timed mock tests from a whole course folder.
|
| 83 |
+
|
| 84 |
+
**Course library (SDE-Prep)**
|
| 85 |
+
- Course PDFs from SDE-Prep's Notes tab are read once on the server and shared by every student.
|
| 86 |
+
- Ask about the PDF that's open: answers come from that PDF first, then the rest of its course, and each
|
| 87 |
+
source says where in the PDF it is (SDE-Prep scrolls there when it's clicked).
|
| 88 |
+
- Flashcards, quizzes and summaries from a course PDF; saved decks show up in the Review tab here.
|
| 89 |
+
|
| 90 |
+
**Accounts and running a pilot**
|
| 91 |
+
- Sign up, sign in, change or reset password (by email), delete account.
|
| 92 |
+
- Works on phones, and can be added to the home screen like an app.
|
| 93 |
+
- New accounts get a "Getting started" folder with sample notes, so the first question works right away.
|
| 94 |
+
- 👍 / 👎 on every answer and a feedback form.
|
| 95 |
+
- Admin page with usage, estimated AI cost and feedback; an optional monthly AI budget.
|
| 96 |
+
- Error alerts to Slack or Discord, weekly encrypted backups, and an uptime check.
|
| 97 |
|
| 98 |
+
---
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
+
## How it works
|
| 101 |
|
| 102 |
+
NoteScanner has three main flows: **saving a note**, **answering a question**, and **making study material**.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
+
### 1. Saving a note
|
| 105 |
|
| 106 |
+
```
|
| 107 |
+
You upload a file
|
| 108 |
+
│
|
| 109 |
+
▼
|
| 110 |
+
Quick check: type and size ──► file is queued, you see "processing"
|
| 111 |
+
│
|
| 112 |
+
▼
|
| 113 |
+
Read the text out of the file
|
| 114 |
+
• PDF → Sarvam Vision (backup: PyMuPDF reads the PDF's built-in text)
|
| 115 |
+
• Photo → Sarvam Vision (backup: Tesseract)
|
| 116 |
+
• .txt / .md / .csv / .json / .log → used as is
|
| 117 |
+
│
|
| 118 |
+
▼
|
| 119 |
+
Note which page each part of the text came from (PDFs)
|
| 120 |
+
│
|
| 121 |
+
▼
|
| 122 |
+
Cut the text into short overlapping passages (about 750 characters each)
|
| 123 |
+
│
|
| 124 |
+
▼
|
| 125 |
+
Turn each passage into a "meaning fingerprint" (a list of numbers that
|
| 126 |
+
captures what the passage is about). This runs on our own server, for free.
|
| 127 |
+
│
|
| 128 |
+
▼
|
| 129 |
+
Save passages + fingerprints in ChromaDB, and the full text separately
|
| 130 |
+
│
|
| 131 |
+
▼
|
| 132 |
+
Only now does the file appear in your folder. If any step fails, you see an error and
|
| 133 |
+
the file never shows up half-saved.
|
| 134 |
+
```
|
| 135 |
|
| 136 |
+
Reading a long scanned PDF can take a minute or two, which is why this happens in the background.
|
| 137 |
|
| 138 |
+
### 2. Answering a question
|
|
|
|
| 139 |
|
| 140 |
+
```
|
| 141 |
+
You ask a question (optionally about a highlighted passage)
|
| 142 |
+
│
|
| 143 |
+
▼
|
| 144 |
+
Turn the question into a meaning fingerprint
|
| 145 |
+
│
|
| 146 |
+
▼
|
| 147 |
+
Look for the closest-matching passages, in this order:
|
| 148 |
+
1. Files attached to this chat with + (kept in memory for 2 hours, never saved)
|
| 149 |
+
2. The file you have open
|
| 150 |
+
3. Other files in the same course folder
|
| 151 |
+
4. All your other notes
|
| 152 |
+
Use the first place that has a good enough match. If none does, use the best match found.
|
| 153 |
+
Keep up to 8 passages. Files marked "main source" get a small boost.
|
| 154 |
+
│
|
| 155 |
+
▼
|
| 156 |
+
Send the question + those passages to Sarvam AI (sarvam-105b) with these rules:
|
| 157 |
+
• Use the notes first and refer to them.
|
| 158 |
+
• If the notes don't fully answer it, add standard textbook knowledge for the
|
| 159 |
+
same subject and label it "📖 Beyond notes".
|
| 160 |
+
• Stay within the course's subject.
|
| 161 |
+
• Write in the student's chosen language.
|
| 162 |
+
│
|
| 163 |
+
▼
|
| 164 |
+
The answer streams back to you, with the source files and page numbers.
|
| 165 |
+
```
|
| 166 |
|
| 167 |
+
Search works by **meaning**, not exact words: a question about "how fast a reaction happens" can
|
| 168 |
+
find a passage about "rate of reaction".
|
|
|
|
|
|
|
| 169 |
|
| 170 |
+
### 3. Making study material
|
| 171 |
|
| 172 |
+
```
|
| 173 |
+
You open a file and choose Flashcards, Quiz or Summary
|
| 174 |
+
│
|
| 175 |
+
▼
|
| 176 |
+
Collect the text: the open file, plus short parts of other files in the same course folder
|
| 177 |
+
│
|
| 178 |
+
▼
|
| 179 |
+
Send it to Sarvam AI (sarvam-30b):
|
| 180 |
+
• Flashcards and quizzes: about 70% straight from the notes, about 30% on closely
|
| 181 |
+
related topics from the same subject (those are labelled "📖 Beyond notes")
|
| 182 |
+
• Quizzes: 4 options each, one-line explanation, answer order shuffled
|
| 183 |
+
• Summaries: 100–150 words, only from the notes
|
| 184 |
+
│
|
| 185 |
+
▼
|
| 186 |
+
Check the result is in the right format. Retry up to 3 times if not.
|
| 187 |
+
If it still fails, show an error. NoteScanner never makes up questions on its own,
|
| 188 |
+
because a wrong answer key is worse than no answer key.
|
| 189 |
+
```
|
| 190 |
|
| 191 |
+
Saved flashcards follow the same idea as Anki: each time you review a card you grade it
|
| 192 |
+
(Again / Hard / Good / Easy), and NoteScanner decides when to show it next. Easy cards come back
|
| 193 |
+
after longer and longer gaps; cards you forget come back in 10 minutes.
|
| 194 |
|
| 195 |
+
### 4. The shared course library
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
+
SDE-Prep's Notes tab shows course PDFs from a public Supabase Storage bucket. Instead of every student
|
| 198 |
+
uploading the same PDFs, the server reads each one **once** and keeps it in two shared collections.
|
| 199 |
|
| 200 |
+
```
|
| 201 |
+
scripts/index_library.py (or POST /admin/library/sync, or every LIBRARY_SYNC_HOURS)
|
| 202 |
+
│
|
| 203 |
+
▼
|
| 204 |
+
List the bucket. Skip PDFs whose eTag hasn't changed; remove PDFs that were deleted.
|
| 205 |
+
│
|
| 206 |
+
▼
|
| 207 |
+
For each page:
|
| 208 |
+
• typed text → PyMuPDF (free)
|
| 209 |
+
• handwriting/scan → cut into page-shaped pieces at blank rows (no line of writing is split),
|
| 210 |
+
read with Sarvam Vision, at most 10 pieces per job (Sarvam's limit);
|
| 211 |
+
Tesseract when there's no Sarvam key
|
| 212 |
+
│
|
| 213 |
+
▼
|
| 214 |
+
Cut into passages and embed them, like a note. Each passage remembers its page and how far down
|
| 215 |
+
the page it starts, so SDE-Prep can scroll to the exact spot.
|
| 216 |
+
```
|
| 217 |
|
| 218 |
+
When SDE-Prep asks a question it sends `library_path` (the open PDF). The search ranks that PDF and the
|
| 219 |
+
rest of its course together, with a small lead for the open PDF, so a lecture that clearly answers the
|
| 220 |
+
question wins. The student's own notes are used only when they really match.
|
| 221 |
|
| 222 |
+
---
|
| 223 |
|
| 224 |
+
## Tech stack
|
| 225 |
+
|
| 226 |
+
| Part | Tool | What it's used for |
|
| 227 |
+
|---|---|---|
|
| 228 |
+
| **Website** | React 19 + Vite | The app you see in the browser. |
|
| 229 |
+
| | react-markdown, KaTeX | Showing formatted answers and math. |
|
| 230 |
+
| **Server** | Python 3.11 + FastAPI (run with Uvicorn) | Handles sign-in, uploads, questions and study tools. |
|
| 231 |
+
| **Reading files** | Sarvam Vision (Sarvam AI Document Intelligence) | Reads text from PDFs, scans and handwriting. |
|
| 232 |
+
| | PyMuPDF | Backup for PDFs that already contain text. |
|
| 233 |
+
| | Tesseract | Backup for photos of printed text. |
|
| 234 |
+
| **Search by meaning** | `all-MiniLM-L6-v2` (sentence-transformers) | A small free model, running on our server, that makes the "meaning fingerprints". |
|
| 235 |
+
| | LangChain text splitter | Cuts notes into short passages. |
|
| 236 |
+
| **Storage** | ChromaDB (Chroma Cloud or self-hosted) | Stores note passages and finds the closest matches to a question. Also stores accounts, folders, decks and usage. |
|
| 237 |
+
| **Writing answers** | Sarvam AI chat models | `sarvam-105b` writes answers; `sarvam-30b` writes flashcards, quizzes and summaries. |
|
| 238 |
+
| **Passwords** | bcrypt | Passwords are stored scrambled, never as plain text. |
|
| 239 |
+
| **Hosting** | GitHub Pages | Hosts the website. |
|
| 240 |
+
| | Hugging Face Spaces (Docker) | Hosts the server. |
|
| 241 |
+
| | GitHub Actions | Runs tests on every change, deploys, makes weekly backups, checks the site is up. |
|
| 242 |
+
| **Testing** | pytest, ESLint | Server tests and website code checks. |
|
| 243 |
+
|
| 244 |
+
Why Sarvam AI: it is built for Indian languages, which is what lets NoteScanner answer in 10 of them.
|
| 245 |
|
| 246 |
+
---
|
| 247 |
|
| 248 |
+
## Project structure
|
|
|
|
| 249 |
|
| 250 |
+
```
|
| 251 |
+
NoteScanner/
|
| 252 |
+
├── backend/ The server (Python)
|
| 253 |
+
│ ├── api.py Starts the app: error handling, request limits, /health, /config
|
| 254 |
+
│ ├── settings.py All settings, limits and search thresholds in one place
|
| 255 |
+
│ ├── routes/ The server's web addresses, grouped by feature
|
| 256 |
+
│ │ ├── account.py Sign up, sign in, passwords, preferences, delete account
|
| 257 |
+
│ │ ├── files.py Folders, uploads, renaming, moving, viewing and editing text
|
| 258 |
+
│ │ ├── chat.py Asking questions, chat attachments (+)
|
| 259 |
+
│ │ ├── study.py Flashcards, quizzes, summaries, decks, Today, exam mode
|
| 260 |
+
│ │ ├── onenote.py OneNote connect and import
|
| 261 |
+
│ │ ├── admin.py Usage and feedback page for admins
|
| 262 |
+
│ │ └── library.py Shared course library: status, admin sync
|
| 263 |
+
│ │
|
| 264 |
+
│ ├── library.py Shared course library: reads course PDFs once, searches them
|
| 265 |
+
│ ├── uploads.py Reads text out of files; background upload queue
|
| 266 |
+
│ ├── extract_api.py Tesseract backup for photos
|
| 267 |
+
│ ├── pages.py Works out page numbers for PDF text
|
| 268 |
+
│ ├── ingest_api.py Cuts text into passages and makes meaning fingerprints
|
| 269 |
+
│ ├── search.py Finds the passages that answer a question
|
| 270 |
+
│ ├── llm_pipeline.py Everything that talks to Sarvam AI: reading files, answers, study material
|
| 271 |
+
│ ├── chat_cache.py Files attached to one chat (memory only, deleted after 2 hours)
|
| 272 |
+
│ ├── study_store.py Saved decks and the review schedule
|
| 273 |
+
│ ├── chroma_store.py All reads and writes to ChromaDB
|
| 274 |
+
│ ├── vfs_tree.py, paths.py, file_meta.py Folder tree and file details (e.g. "main source")
|
| 275 |
+
│ ├── auth.py, deps.py Passwords, sign-in sessions, who is making a request
|
| 276 |
+
│ ├── rate_limit.py Request limits
|
| 277 |
+
│ ├── usage.py Daily usage per student, estimated AI cost, monthly budget
|
| 278 |
+
│ ├── preferences.py Answer language, reminder settings
|
| 279 |
+
│ ├── reminders.py, mailer.py Daily review emails and password-reset emails
|
| 280 |
+
│ ├── feedback.py, alerts.py Answer ratings and feedback; error alerts to Slack/Discord
|
| 281 |
+
│ ├── onenote_sync.py Imports OneNote pages through Microsoft sign-in
|
| 282 |
+
│ ├── starter_notes.py "Getting started" folder for new accounts
|
| 283 |
+
│ └── legacy_migration.py One-time move of data saved by older versions
|
| 284 |
+
│
|
| 285 |
+
├── frontend/my-app/ The website (React)
|
| 286 |
+
│ ├── public/ Icons, app screenshot, files that let it install on phones
|
| 287 |
+
│ └── src/
|
| 288 |
+
│ ├── pages/ Full pages: Home (main app), Login, Register, ResetPassword, ChatPage (signed-out landing)
|
| 289 |
+
│ ├── components/ Parts of the page: Explorer (folders), QueryInterface (chat),
|
| 290 |
+
│ │ StudyPanel, StudyDecks, StudyToday, ExamMode, FileTextView,
|
| 291 |
+
│ │ upload progress, settings, feedback, privacy note, admin page
|
| 292 |
+
│ ├── auth.js, config.js Sign-in state and the server address
|
| 293 |
+
│ ├── embed.js, embed.css Study AI mode: inside SDE-Prep, with its name and colours
|
| 294 |
+
│ ├── localFileStore.js Keeps your original files on your device for viewing
|
| 295 |
+
│ ├── localDiskFolder.js Optional: mirror your folders into a "NoteScanner" folder on your computer
|
| 296 |
+
│ └── studyApi.js, studyUtils.js, chatHistory.js, virtualPath.js Small helpers
|
| 297 |
+
│
|
| 298 |
+
├── scripts/ backup_chroma.py, restore_chroma.py, answer_quality.py,
|
| 299 |
+
│ index_library.py (index the shared course library)
|
| 300 |
+
├── evals/ Sample questions for the answer-quality test (see evals/README.md)
|
| 301 |
+
├── tests/ Server tests (pytest)
|
| 302 |
+
├── .github/workflows/ Tests, deploys, weekly backup, uptime check
|
| 303 |
+
├── Dockerfile Builds the server for Hugging Face Spaces
|
| 304 |
+
├── docker-compose.yml Runs server + website + ChromaDB together on your computer
|
| 305 |
+
├── requirements.txt Python packages (requirements-dev.txt adds test tools)
|
| 306 |
+
└── DEPLOYMENT.md How to put it online
|
| 307 |
+
```
|
| 308 |
|
| 309 |
+
---
|
| 310 |
|
| 311 |
+
## Running it on your computer
|
| 312 |
|
| 313 |
+
### 1. Create a `.env` file
|
| 314 |
|
| 315 |
+
In the project root, create a file named `.env`:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
|
| 317 |
+
```bash
|
| 318 |
+
SARVAM_API_KEY=your-sarvam-key
|
| 319 |
|
| 320 |
+
# Option A: Chroma Cloud
|
| 321 |
+
CHROMA_API_KEY=...
|
| 322 |
+
CHROMA_TENANT=...
|
| 323 |
+
CHROMA_DATABASE=...
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
|
| 325 |
+
# Option B: your own ChromaDB (Docker Compose below starts one for you)
|
| 326 |
+
# CHROMA_HOST=localhost
|
| 327 |
+
# CHROMA_PORT=8100
|
| 328 |
+
```
|
| 329 |
|
| 330 |
+
Get a Sarvam API key at [sarvam.ai](https://www.sarvam.ai). Without one, uploads fall back to
|
| 331 |
+
PyMuPDF and Tesseract, but questions and study tools won't work.
|
| 332 |
|
| 333 |
+
### 2a. With Docker (easiest)
|
| 334 |
|
| 335 |
```bash
|
| 336 |
docker compose up --build
|
| 337 |
```
|
| 338 |
|
| 339 |
+
- Website: http://localhost:5173
|
| 340 |
+
- Server: http://localhost:8000 (interactive API docs at http://localhost:8000/docs)
|
| 341 |
+
- ChromaDB: http://localhost:8100
|
| 342 |
|
| 343 |
+
### 2b. Without Docker
|
|
|
|
| 344 |
|
| 345 |
+
You need Python 3.11, Node 20, and Tesseract (`brew install tesseract` on macOS,
|
| 346 |
+
`apt install tesseract-ocr` on Ubuntu). For storage, use Chroma Cloud or start just ChromaDB with
|
| 347 |
+
`docker compose up chromadb`.
|
| 348 |
|
| 349 |
```bash
|
| 350 |
+
# Server
|
| 351 |
+
python3.11 -m venv venv && source venv/bin/activate
|
| 352 |
+
pip install -r requirements-dev.txt
|
| 353 |
+
uvicorn backend.api:app --host 0.0.0.0 --port 8000
|
| 354 |
+
|
| 355 |
+
# Website (in a second terminal)
|
| 356 |
+
cd frontend/my-app
|
| 357 |
+
npm ci
|
| 358 |
+
npm run dev -- --host
|
| 359 |
```
|
| 360 |
|
| 361 |
+
The first start downloads the small search model (about 90 MB), so it takes a little longer.
|
| 362 |
|
| 363 |
+
### Tests
|
| 364 |
|
| 365 |
```bash
|
| 366 |
+
python -m pytest -q tests # server (no internet or AI key needed; Tesseract required)
|
| 367 |
+
cd frontend/my-app && npx eslint . && npm run build # website
|
|
|
|
|
|
|
| 368 |
```
|
| 369 |
|
| 370 |
+
Both run automatically on every push and pull request (`.github/workflows/ci.yml`).
|
| 371 |
|
| 372 |
+
---
|
| 373 |
+
|
| 374 |
+
## Putting it online
|
|
|
|
|
|
|
| 375 |
|
| 376 |
+
- Website → **GitHub Pages**, deployed on every push to `main`.
|
| 377 |
+
- Server → **Hugging Face Spaces** (Docker), deployed on every push to `main` once `HF_TOKEN` is set.
|
| 378 |
|
| 379 |
+
Step-by-step instructions, backups and checks are in [DEPLOYMENT.md](DEPLOYMENT.md).
|
|
|
|
|
|
|
|
|
|
| 380 |
|
| 381 |
+
> Run the server as **one process** (one Uvicorn worker). Upload jobs, chat attachments and request
|
| 382 |
+
> limits are kept in the server's memory.
|
| 383 |
|
| 384 |
+
---
|
|
|
|
|
|
|
|
|
|
| 385 |
|
| 386 |
+
## Reference
|
| 387 |
+
|
| 388 |
+
### Settings
|
| 389 |
+
|
| 390 |
+
**Required:** `SARVAM_API_KEY`, plus ChromaDB settings:
|
| 391 |
+
`CHROMA_API_KEY`, `CHROMA_TENANT`, `CHROMA_DATABASE` (Chroma Cloud) **or** `CHROMA_HOST`,
|
| 392 |
+
`CHROMA_PORT`, `CHROMA_SSL` (your own ChromaDB).
|
| 393 |
+
|
| 394 |
+
**Optional** (default in brackets):
|
| 395 |
+
|
| 396 |
+
| Area | Settings |
|
| 397 |
+
|---|---|
|
| 398 |
+
| Sarvam AI | `SARVAM_API_BASE`, `SARVAM_MODEL_RAG` (`sarvam-105b`), `SARVAM_MODEL_STUDY` (`sarvam-30b`), `SARVAM_DOC_INTEL_LANGUAGE` (`en-IN`), `SARVAM_DOC_INTEL_TIMEOUT` (180 s) |
|
| 399 |
+
| Security and sizes | `CORS_ORIGINS` (localhost + `https://cherie-dips.github.io`), `SESSION_TTL_DAYS` (14), `MAX_UPLOAD_MB` (20), `MAX_CHAT_UPLOAD_CHARS` (300000), `CHAT_CACHE_TTL_SECONDS` (7200), `USER_DOCUMENT_MAX_BYTES` (2000000), `RATE_LIMIT_MULTIPLIER` (1) |
|
| 400 |
+
| Password-reset email | `FRONTEND_URL`, `SMTP_HOST`, `SMTP_PORT` (587), `SMTP_USERNAME`, `SMTP_PASSWORD`, `SMTP_FROM`, `SMTP_STARTTLS` (true). Turned on only when `SMTP_HOST` and `SMTP_FROM` are set. |
|
| 401 |
+
| OneNote | `MICROSOFT_CLIENT_ID`, `MICROSOFT_CLIENT_SECRET`, `MICROSOFT_REDIRECT_URI` |
|
| 402 |
+
| Course library | `LIBRARY_ENABLED` (true), `LIBRARY_SUPABASE_URL` / `LIBRARY_SUPABASE_KEY` / `LIBRARY_BUCKET` (SDE-Prep's public bucket), `LIBRARY_PREFIXES` (`plaksha-university`), `LIBRARY_OCR` (`auto`), `LIBRARY_SYNC_HOURS` (0 = by hand). See [DEPLOYMENT.md](DEPLOYMENT.md#5-shared-course-library-and-sde-prep-study-ai--ask-ai). |
|
| 403 |
+
| Pilot | `ADMIN_EMAILS`, `ALERT_WEBHOOK_URL`, `AI_PRICE_PER_PAGE`, `AI_PRICE_PER_1K_INPUT_TOKENS`, `AI_PRICE_PER_1K_OUTPUT_TOKENS`, `AI_PRICE_CURRENCY` (INR), `AI_MONTHLY_BUDGET` (0 = off), `APP_TIMEZONE` (Asia/Kolkata), `REMINDER_HOUR` (8), `REMINDERS_ENABLED` (true), `STARTER_NOTES` (true) |
|
| 404 |
+
|
| 405 |
+
Search thresholds (how close a match must be before it's used) are the `MIN_SCORE_*` values in
|
| 406 |
+
`backend/settings.py`.
|
| 407 |
+
|
| 408 |
+
### Request limits
|
| 409 |
+
|
| 410 |
+
Limits stop password guessing and keep AI costs predictable. They are the `LIMIT_*` values in
|
| 411 |
+
`backend/settings.py`; `RATE_LIMIT_MULTIPLIER` raises or lowers all of them at once.
|
| 412 |
+
|
| 413 |
+
| What | Limit |
|
| 414 |
+
|---|---|
|
| 415 |
+
| Any request | 1200 / minute per network address, 300 / minute per signed-in browser (`/health` is never limited) |
|
| 416 |
+
| Sign-up / login | 50 sign-ups per hour per address; 10 login attempts per 15 min per email and address |
|
| 417 |
+
| Password checks, forgot / reset password | 10 per 15 min per user; 3 reset emails per hour per email; 20 reset attempts per hour per address |
|
| 418 |
+
| Uploads (notes and chat attachments) | 30 per 10 min and **200 per day** per user |
|
| 419 |
+
| Questions | 60 per 10 min and **300 per day** per user |
|
| 420 |
+
| Flashcards / quizzes / summaries | 20 per 10 min and **100 per day** per user |
|
| 421 |
+
| Folder changes, saving edited text, decks | 120 per minute; 60 per 10 min; 60 per 10 min per user |
|
| 422 |
+
| Delete all notes, OneNote connect / sync | 5 per hour; 10 and 5 per 10 min per user |
|
| 423 |
+
|
| 424 |
+
Going over a limit returns HTTP `429` with a `Retry-After` header and a clear message, such as
|
| 425 |
+
"You've reached the daily limit of 300 questions…". Counters reset when the server restarts.
|
| 426 |
+
|
| 427 |
+
### API routes
|
| 428 |
+
|
| 429 |
+
Sign-in uses the `X-Session-Id` header. Sessions end after `SESSION_TTL_DAYS` (default 14). Anything
|
| 430 |
+
that saves data or uses AI needs a signed-in user. Full interactive docs are at `/docs` on the running server.
|
| 431 |
+
|
| 432 |
+
| Area | Routes |
|
| 433 |
+
|---|---|
|
| 434 |
+
| Accounts | `POST /register`, `POST /login`, `POST /logout`, `GET /me`, `GET /guest_id`, `POST /account/change_password`, `POST /account/delete`, `POST /password/forgot`, `POST /password/reset`, `GET/POST /account/preferences` |
|
| 435 |
+
| Files | `GET /list_tree`, `POST /create_folder`, `POST /create_file`, `POST /upload_note`, `GET /jobs`, `GET /jobs/{job_id}`, `POST /move_path`, `POST /rename_path`, `POST /delete_path`, `GET/POST /file_text`, `GET/POST /file_meta`, `DELETE /notes` |
|
| 436 |
+
| Chat | `POST /query_folder`, `POST /query_folder/stream`, `POST /chat/upload_ephemeral`, `POST /chat/session/clear` |
|
| 437 |
+
| Study | `POST /study/generate`, `POST /study/summary` (old name `/study/mindmap` still works), `POST /study/decks`, `GET /study/decks`, `GET /study/decks/{id}/cards`, `POST /study/cards/{id}/review`, `DELETE /study/decks/{id}`, `GET /study/decks/{id}/export`, `GET /study/dashboard`, `POST /study/mcq_results`, `POST /study/exam`, `POST /study/exam_plan`, `GET /study/exams`, `DELETE /study/exams/{id}` |
|
| 438 |
+
| Feedback and admin | `POST /feedback`, `GET /admin/stats`, `GET /admin/feedback` (admins only) |
|
| 439 |
+
| Course library | `GET /library/status` (public), `GET /admin/library`, `POST /admin/library/sync` (admins only). `library_path` on `/query_folder`, `/query_folder/stream`, `/study/generate` and `/study/summary` asks about a course PDF |
|
| 440 |
+
| OneNote | `GET /integrations/onenote/status`, `GET /integrations/onenote/auth_url`, `GET /integrations/onenote/callback`, `POST /integrations/onenote/sync` |
|
| 441 |
+
| Service | `GET /health`, `GET /config` |
|
| 442 |
+
|
| 443 |
+
`/query_folder/stream` sends one JSON object per line: first `meta` (the sources), then `delta`
|
| 444 |
+
lines with pieces of the answer, then `done` (or `error`).
|
| 445 |
+
|
| 446 |
+
### What is stored where (ChromaDB collections)
|
| 447 |
+
|
| 448 |
+
| Collection | Contents |
|
| 449 |
+
|---|---|
|
| 450 |
+
| `users`, `sessions`, `password_resets` | Accounts and sign-ins (only a scrambled copy of each reset link is kept) |
|
| 451 |
+
| `user_documents` | The full text of every file |
|
| 452 |
+
| `user_{id}_notes` | Searchable passages, their meaning fingerprints, and file path / course / page |
|
| 453 |
+
| `user_{id}_vfs` | The folder tree and file details |
|
| 454 |
+
| `user_{id}_study` | Decks, cards and their review schedule, quiz results, exam plans |
|
| 455 |
+
| `usage_daily`, `feedback` | Daily usage counts per student; ratings and feedback |
|
| 456 |
+
| `library_notes` | Shared course library: passages, fingerprints, and path / course / page / position |
|
| 457 |
+
| `library_documents` | Shared course library: one record per PDF (status, page counts) and its full text |
|
| 458 |
+
| `onenote_tokens`, `onenote_oauth_states` | OneNote connection |
|
| 459 |
+
|
| 460 |
+
Chroma Cloud allows at most 300 records per read or write, 16 KB per record and ids of up to 128 bytes.
|
| 461 |
+
`chroma_store.py` splits reads, writes and large files to fit, so big libraries and long file names work.
|
backend/alerts.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Error alerts to a chat channel (Slack, Discord or similar incoming webhook) via ALERT_WEBHOOK_URL.
|
| 3 |
+
Each kind of alert is sent at most once every 10 minutes so an outage doesn't flood the channel.
|
| 4 |
+
"""
|
| 5 |
+
import logging
|
| 6 |
+
import threading
|
| 7 |
+
import time
|
| 8 |
+
|
| 9 |
+
import httpx
|
| 10 |
+
|
| 11 |
+
from backend import settings
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
THROTTLE_SECONDS = 600
|
| 16 |
+
_last_sent: dict[str, float] = {}
|
| 17 |
+
_lock = threading.Lock()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _post(text: str) -> None:
|
| 21 |
+
try:
|
| 22 |
+
# "text" is read by Slack-style webhooks, "content" by Discord.
|
| 23 |
+
httpx.post(settings.ALERT_WEBHOOK_URL, json={"text": text, "content": text}, timeout=10)
|
| 24 |
+
except Exception:
|
| 25 |
+
logger.warning("Could not send alert", exc_info=True)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def notify(kind: str, message: str) -> bool:
|
| 29 |
+
"""Send an alert unless the same kind was sent recently. Returns True if one was sent."""
|
| 30 |
+
if not settings.ALERT_WEBHOOK_URL:
|
| 31 |
+
return False
|
| 32 |
+
now = time.time()
|
| 33 |
+
with _lock:
|
| 34 |
+
if now - _last_sent.get(kind, 0) < THROTTLE_SECONDS:
|
| 35 |
+
return False
|
| 36 |
+
_last_sent[kind] = now
|
| 37 |
+
text = f"NoteScanner alert ({kind}): {message[:1500]}"
|
| 38 |
+
threading.Thread(target=_post, args=(text,), name="alert", daemon=True).start()
|
| 39 |
+
return True
|
backend/api.py
CHANGED
|
@@ -1,1199 +1,100 @@
|
|
| 1 |
-
|
| 2 |
-
from fastapi.responses import JSONResponse, HTMLResponse
|
| 3 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
-
import os
|
| 5 |
-
import re
|
| 6 |
-
import uuid
|
| 7 |
-
import time
|
| 8 |
from dotenv import load_dotenv
|
| 9 |
-
import copy
|
| 10 |
-
import json
|
| 11 |
-
from datetime import datetime
|
| 12 |
-
from typing import Annotated
|
| 13 |
-
from sentence_transformers import SentenceTransformer
|
| 14 |
-
|
| 15 |
-
from backend.chroma_store import (
|
| 16 |
-
user_exists_by_email,
|
| 17 |
-
user_create,
|
| 18 |
-
user_get_by_email,
|
| 19 |
-
user_get_by_id,
|
| 20 |
-
user_document_upsert,
|
| 21 |
-
user_document_delete_many,
|
| 22 |
-
user_document_delete_by_path,
|
| 23 |
-
get_user_collection,
|
| 24 |
-
delete_user_notes_collection,
|
| 25 |
-
delete_user_notes_by_paths,
|
| 26 |
-
vfs_get_tree,
|
| 27 |
-
vfs_set_tree,
|
| 28 |
-
delete_user_vfs_collection,
|
| 29 |
-
user_document_rename_path,
|
| 30 |
-
user_documents_relocate_prefix,
|
| 31 |
-
onenote_oauth_state_create,
|
| 32 |
-
onenote_oauth_state_pop_user_id,
|
| 33 |
-
onenote_token_get,
|
| 34 |
-
onenote_token_upsert,
|
| 35 |
-
user_document_get_content,
|
| 36 |
-
user_notes_concat_text_for_path,
|
| 37 |
-
)
|
| 38 |
-
|
| 39 |
-
from backend.file_meta import (
|
| 40 |
-
load_file_meta,
|
| 41 |
-
set_entry,
|
| 42 |
-
delete_key,
|
| 43 |
-
delete_keys_for_prefix,
|
| 44 |
-
chunk_paths_for_file,
|
| 45 |
-
file_meta_rename_path,
|
| 46 |
-
file_meta_relocate_prefix,
|
| 47 |
-
)
|
| 48 |
-
from backend.ingest_api import (
|
| 49 |
-
ingest_text_for_path,
|
| 50 |
-
refresh_metadata_for_paths,
|
| 51 |
-
chunks_relocate_path,
|
| 52 |
-
chunks_relocate_folder_prefix,
|
| 53 |
-
)
|
| 54 |
-
from backend.vfs_tree import (
|
| 55 |
-
tree_add_folder,
|
| 56 |
-
tree_add_file,
|
| 57 |
-
tree_remove_path,
|
| 58 |
-
tree_move_path,
|
| 59 |
-
tree_has_folder,
|
| 60 |
-
flatten_file_paths,
|
| 61 |
-
)
|
| 62 |
-
from backend import llm_pipeline
|
| 63 |
-
from backend import onenote_sync
|
| 64 |
-
|
| 65 |
-
from backend.auth import (
|
| 66 |
-
hash_password,
|
| 67 |
-
verify_password,
|
| 68 |
-
create_session,
|
| 69 |
-
get_user_id_from_session,
|
| 70 |
-
get_effective_user,
|
| 71 |
-
SESSION_HEADER,
|
| 72 |
-
GUEST_HEADER,
|
| 73 |
-
)
|
| 74 |
|
|
|
|
| 75 |
load_dotenv()
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
_chat_upload_cache: dict[str, list[dict]] = {}
|
| 80 |
-
|
| 81 |
-
app.add_middleware(
|
| 82 |
-
CORSMiddleware,
|
| 83 |
-
allow_origins=["*"],
|
| 84 |
-
allow_credentials=True,
|
| 85 |
-
allow_methods=["*"],
|
| 86 |
-
allow_headers=["*"],
|
| 87 |
-
)
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
def _get_query_embedder():
|
| 91 |
-
global _query_embed_model
|
| 92 |
-
if _query_embed_model is None:
|
| 93 |
-
_query_embed_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 94 |
-
return _query_embed_model
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
def _chat_cache_key(user_id: str, chat_session_id: str) -> str:
|
| 98 |
-
return f"{user_id}::{(chat_session_id or '').strip()}"
|
| 99 |
-
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
_chat_upload_cache.setdefault(key, []).append(item)
|
| 105 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
return list(_chat_upload_cache.get(key, []))
|
| 110 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
-
def _chat_cache_clear(user_id: str, chat_session_id: str) -> int:
|
| 113 |
-
key = _chat_cache_key(user_id, chat_session_id)
|
| 114 |
-
old = _chat_upload_cache.pop(key, [])
|
| 115 |
-
return len(old)
|
| 116 |
|
| 117 |
-
|
| 118 |
-
@app.post("/register")
|
| 119 |
-
def register(email: str = Form(...), password: str = Form(...), name: str = Form("")):
|
| 120 |
-
try:
|
| 121 |
-
if user_exists_by_email(email):
|
| 122 |
-
return JSONResponse({"error": "Email already registered."}, status_code=400)
|
| 123 |
-
user_id = user_create(
|
| 124 |
-
email.lower(),
|
| 125 |
-
hash_password(password),
|
| 126 |
-
name or email.split("@")[0],
|
| 127 |
-
)
|
| 128 |
-
session_id = create_session(user_id)
|
| 129 |
-
u = user_get_by_id(user_id)
|
| 130 |
-
display_name = (u and u.get("name")) or email.split("@")[0]
|
| 131 |
-
return JSONResponse({"session_id": session_id, "user_id": user_id, "name": display_name})
|
| 132 |
-
except Exception:
|
| 133 |
-
return JSONResponse(
|
| 134 |
-
{"error": "Database unavailable. Please try again later."},
|
| 135 |
-
status_code=503,
|
| 136 |
-
)
|
| 137 |
|
| 138 |
|
| 139 |
-
@app.
|
| 140 |
-
def
|
|
|
|
| 141 |
try:
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
session_id = create_session(user_id)
|
| 147 |
-
name = user.get("name") or (user.get("email") or "").split("@")[0]
|
| 148 |
-
return JSONResponse({"session_id": session_id, "user_id": user_id, "name": name})
|
| 149 |
-
except Exception:
|
| 150 |
return JSONResponse(
|
| 151 |
-
{"error": "
|
| 152 |
-
status_code=
|
| 153 |
)
|
| 154 |
|
| 155 |
|
| 156 |
-
@app.
|
| 157 |
-
def
|
| 158 |
-
"""Return current user info (name) for the session. Requires valid X-Session-Id."""
|
| 159 |
-
session_id = request.headers.get(SESSION_HEADER)
|
| 160 |
-
user_id = get_user_id_from_session(session_id)
|
| 161 |
-
if not user_id:
|
| 162 |
-
return JSONResponse({"error": "Not signed in."}, status_code=401)
|
| 163 |
-
user = user_get_by_id(user_id)
|
| 164 |
-
if not user:
|
| 165 |
-
return JSONResponse({"error": "User not found."}, status_code=404)
|
| 166 |
-
name = user.get("name") or (user.get("email") or "").split("@")[0]
|
| 167 |
-
return JSONResponse({"name": name or "User"})
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
@app.get("/guest_id")
|
| 171 |
-
def get_guest_id():
|
| 172 |
-
"""Return a new guest id for anonymous use. Frontend stores it and sends X-Guest-Id header."""
|
| 173 |
-
return JSONResponse({"guest_id": str(uuid.uuid4())})
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
# ---------- Resolve user/guest from request ----------
|
| 177 |
-
def get_effective_user_dep(request: Request) -> tuple[str, bool]:
|
| 178 |
-
try:
|
| 179 |
-
return get_effective_user(request)
|
| 180 |
-
except ValueError as e:
|
| 181 |
-
raise HTTPException(status_code=400, detail=str(e))
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
def _require_signed_in(effective: tuple[str, bool]) -> str:
|
| 185 |
-
user_id, is_guest = effective
|
| 186 |
-
if is_guest:
|
| 187 |
-
raise HTTPException(status_code=401, detail="Sign in required for OneNote integration.")
|
| 188 |
-
return user_id
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
# ---------- Delete file or folder ----------
|
| 192 |
-
def _normalize_relative_path(path: str) -> str:
|
| 193 |
-
"""Use forward slashes and strip leading slashes for cross-platform consistency."""
|
| 194 |
-
if not path or not path.strip():
|
| 195 |
-
return ""
|
| 196 |
-
return path.replace("\\", "/").strip("/")
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
def _is_likely_user_id_segment(seg: str) -> bool:
|
| 200 |
-
if not seg:
|
| 201 |
-
return False
|
| 202 |
-
if seg.startswith("guest_"):
|
| 203 |
-
return True
|
| 204 |
-
if len(seg) == 36 and seg.count("-") == 4:
|
| 205 |
-
return True
|
| 206 |
-
return False
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
def _strip_storage_path(p: str) -> str:
|
| 210 |
"""
|
| 211 |
-
|
| 212 |
-
(
|
| 213 |
"""
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
parts.pop(0)
|
| 220 |
-
if parts and _is_likely_user_id_segment(parts[0]):
|
| 221 |
-
parts.pop(0)
|
| 222 |
-
return "/".join(parts)
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
def _normalize_vfs_tree(tree: list) -> list:
|
| 226 |
-
"""Deep copy of explorer tree with every path passed through _strip_storage_path."""
|
| 227 |
-
out = copy.deepcopy(tree or [])
|
| 228 |
-
|
| 229 |
-
def rec(nodes: list) -> None:
|
| 230 |
-
for n in nodes:
|
| 231 |
-
if "path" in n:
|
| 232 |
-
n["path"] = _strip_storage_path(str(n.get("path") or ""))
|
| 233 |
-
if n.get("type") == "folder":
|
| 234 |
-
rec(n.get("children") or [])
|
| 235 |
-
|
| 236 |
-
rec(out)
|
| 237 |
-
return out
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
def _get_vfs_tree_clean(user_id: str) -> list:
|
| 241 |
-
"""Return vfs tree with no user_notes/legacy id prefixes; persist if corrected."""
|
| 242 |
-
raw = vfs_get_tree(user_id)
|
| 243 |
-
fixed = _normalize_vfs_tree(raw)
|
| 244 |
-
if fixed != raw:
|
| 245 |
-
vfs_set_tree(user_id, fixed)
|
| 246 |
-
return fixed
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
def _vfs_entry_kind(tree: list, target_path: str) -> str | None:
|
| 250 |
-
"""Return 'file', 'folder', or None if path is not in the virtual tree."""
|
| 251 |
-
tp = _strip_storage_path(target_path)
|
| 252 |
-
if not tp:
|
| 253 |
-
return None
|
| 254 |
-
if tp in {p.replace("\\", "/") for p in flatten_file_paths(tree)}:
|
| 255 |
-
return "file"
|
| 256 |
-
|
| 257 |
-
def folder_at(nodes: list) -> bool:
|
| 258 |
-
for n in nodes:
|
| 259 |
-
p = _normalize_relative_path(n.get("path") or "")
|
| 260 |
-
if n.get("type") == "folder":
|
| 261 |
-
if p == tp:
|
| 262 |
-
return True
|
| 263 |
-
if folder_at(n.get("children") or []):
|
| 264 |
-
return True
|
| 265 |
-
return False
|
| 266 |
-
|
| 267 |
-
return "folder" if folder_at(tree) else None
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
def _path_exists_in_vfs(tree: list, rel: str) -> bool:
|
| 271 |
-
rel = _strip_storage_path(rel)
|
| 272 |
-
if rel in {p.replace("\\", "/") for p in flatten_file_paths(tree)}:
|
| 273 |
-
return True
|
| 274 |
-
|
| 275 |
-
def folder_at(nodes: list) -> bool:
|
| 276 |
-
for n in nodes:
|
| 277 |
-
p = _normalize_relative_path(n.get("path") or "")
|
| 278 |
-
if n.get("type") == "folder":
|
| 279 |
-
if p == rel:
|
| 280 |
-
return True
|
| 281 |
-
if folder_at(n.get("children") or []):
|
| 282 |
-
return True
|
| 283 |
-
return False
|
| 284 |
-
|
| 285 |
-
return folder_at(tree)
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
@app.post("/delete_path")
|
| 289 |
-
def delete_path(
|
| 290 |
-
path: str = Form(...),
|
| 291 |
-
kind: str = Form(...), # "file" | "folder"
|
| 292 |
-
effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
|
| 293 |
-
):
|
| 294 |
-
"""Remove a file or folder from the virtual tree and Chroma (no server-side binaries)."""
|
| 295 |
-
user_id, _ = effective
|
| 296 |
-
path = _strip_storage_path(path)
|
| 297 |
-
if ".." in path:
|
| 298 |
-
return JSONResponse({"error": "Invalid path."}, status_code=400)
|
| 299 |
-
tree = _get_vfs_tree_clean(user_id)
|
| 300 |
-
if kind == "file":
|
| 301 |
-
if _vfs_entry_kind(tree, path) != "file":
|
| 302 |
-
return JSONResponse({"error": "Not a file or not found."}, status_code=400)
|
| 303 |
-
stem, extp = os.path.splitext(path)
|
| 304 |
-
vfs_set_tree(user_id, tree_remove_path(tree, path))
|
| 305 |
-
user_document_delete_by_path(user_id, path)
|
| 306 |
-
if extp:
|
| 307 |
-
user_document_delete_by_path(user_id, stem + ".txt")
|
| 308 |
-
try:
|
| 309 |
-
col = get_user_collection(user_id)
|
| 310 |
-
ids_to_drop = []
|
| 311 |
-
for p in (path, path.replace(os.path.splitext(path)[1], ".txt") if extp else path):
|
| 312 |
-
res = col.get(where={"path": p}, include=[])
|
| 313 |
-
ids_to_drop.extend(res.get("ids") or [])
|
| 314 |
-
if ids_to_drop:
|
| 315 |
-
col.delete(ids=ids_to_drop)
|
| 316 |
-
except Exception:
|
| 317 |
-
pass
|
| 318 |
-
delete_key(user_id, path)
|
| 319 |
-
if extp:
|
| 320 |
-
delete_key(user_id, stem + ".txt")
|
| 321 |
-
return JSONResponse({"message": "File deleted."})
|
| 322 |
-
if kind == "folder":
|
| 323 |
-
if _vfs_entry_kind(tree, path) != "folder":
|
| 324 |
-
return JSONResponse({"error": "Not a folder or not found."}, status_code=400)
|
| 325 |
-
vfs_set_tree(user_id, tree_remove_path(tree, path))
|
| 326 |
-
safe_prefix = path.rstrip("/").replace("\\", "/")
|
| 327 |
-
|
| 328 |
-
def path_prefix_match(p):
|
| 329 |
-
np = p.replace("\\", "/")
|
| 330 |
-
return np == safe_prefix or np.startswith(safe_prefix + "/")
|
| 331 |
-
|
| 332 |
-
user_document_delete_many(user_id, path_filter=path_prefix_match)
|
| 333 |
try:
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
p = (meta or {}).get("path") or (meta or {}).get("source_path") or ""
|
| 339 |
-
p = p.replace("\\", "/")
|
| 340 |
-
if p == safe_prefix or p.startswith(safe_prefix + "/"):
|
| 341 |
-
ids_to_drop.append(res["ids"][i])
|
| 342 |
-
if ids_to_drop:
|
| 343 |
-
col.delete(ids=ids_to_drop)
|
| 344 |
-
except Exception:
|
| 345 |
-
pass
|
| 346 |
-
delete_keys_for_prefix(user_id, path)
|
| 347 |
-
return JSONResponse({"message": "Folder deleted."})
|
| 348 |
-
return JSONResponse({"error": "Invalid kind. Use 'file' or 'folder'."}, status_code=400)
|
| 349 |
|
| 350 |
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
""
|
| 358 |
-
|
| 359 |
-
from_path = _strip_storage_path(from_path)
|
| 360 |
-
to_folder = _strip_storage_path(to_folder)
|
| 361 |
-
if ".." in from_path or ".." in to_folder:
|
| 362 |
-
return JSONResponse({"error": "Invalid path."}, status_code=400)
|
| 363 |
-
tree = _get_vfs_tree_clean(user_id)
|
| 364 |
-
kind = _vfs_entry_kind(tree, from_path)
|
| 365 |
-
if not kind:
|
| 366 |
-
return JSONResponse({"error": "Path not found."}, status_code=400)
|
| 367 |
-
name = os.path.basename(from_path.replace("\\", "/"))
|
| 368 |
-
dest_rel = (os.path.join(to_folder, name).replace("\\", "/") if to_folder else name).replace("\\", "/")
|
| 369 |
-
if dest_rel == from_path.replace("\\", "/"):
|
| 370 |
-
return JSONResponse({"message": "Already there.", "path": dest_rel})
|
| 371 |
-
|
| 372 |
-
if _path_exists_in_vfs(tree, dest_rel):
|
| 373 |
-
return JSONResponse({"error": f"'{name}' already exists in destination."}, status_code=400)
|
| 374 |
-
|
| 375 |
-
new_tree = tree_move_path(tree, from_path, to_folder)
|
| 376 |
-
vfs_set_tree(user_id, new_tree)
|
| 377 |
-
|
| 378 |
-
full_dest = dest_rel
|
| 379 |
-
was_file = kind == "file"
|
| 380 |
-
if was_file:
|
| 381 |
-
stem, extp = os.path.splitext(from_path)
|
| 382 |
-
chunks_relocate_path(user_id, from_path, full_dest)
|
| 383 |
-
if extp:
|
| 384 |
-
chunks_relocate_path(
|
| 385 |
-
user_id,
|
| 386 |
-
stem + ".txt",
|
| 387 |
-
os.path.splitext(full_dest)[0] + ".txt",
|
| 388 |
-
)
|
| 389 |
-
user_document_rename_path(user_id, from_path, full_dest)
|
| 390 |
-
if extp:
|
| 391 |
-
user_document_rename_path(
|
| 392 |
-
user_id,
|
| 393 |
-
stem + ".txt",
|
| 394 |
-
os.path.splitext(full_dest)[0] + ".txt",
|
| 395 |
-
)
|
| 396 |
-
file_meta_rename_path(user_id, from_path, full_dest)
|
| 397 |
-
if extp:
|
| 398 |
-
file_meta_rename_path(user_id, stem + ".txt", os.path.splitext(full_dest)[0] + ".txt")
|
| 399 |
-
else:
|
| 400 |
-
old_prefix = from_path.rstrip("/").replace("\\", "/")
|
| 401 |
-
new_prefix = full_dest.rstrip("/").replace("\\", "/")
|
| 402 |
-
chunks_relocate_folder_prefix(user_id, old_prefix, new_prefix)
|
| 403 |
-
user_documents_relocate_prefix(user_id, old_prefix, new_prefix)
|
| 404 |
-
file_meta_relocate_prefix(user_id, old_prefix, new_prefix)
|
| 405 |
-
|
| 406 |
-
return JSONResponse({"message": "Moved.", "path": dest_rel})
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
# ---------- Note operations (VFS + Chroma for signed-in and guest; guest user_id is guest_<uuid>) ----------
|
| 410 |
-
@app.post("/create_folder")
|
| 411 |
-
def create_folder(
|
| 412 |
-
path: str = Form(""),
|
| 413 |
-
name: str = Form(...),
|
| 414 |
-
effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
|
| 415 |
-
):
|
| 416 |
-
user_id, _ = effective
|
| 417 |
-
path = _strip_storage_path(path)
|
| 418 |
-
name = (name or "").strip().replace("\\", "/").strip("/")
|
| 419 |
-
if not name or ".." in name or "/" in name:
|
| 420 |
-
return JSONResponse({"error": "Invalid folder name."}, status_code=400)
|
| 421 |
-
tree = _get_vfs_tree_clean(user_id)
|
| 422 |
-
if path and not tree_has_folder(tree, path):
|
| 423 |
-
return JSONResponse({"error": f"Folder '{path}' does not exist."}, status_code=400)
|
| 424 |
-
vfs_set_tree(user_id, tree_add_folder(tree, path, name))
|
| 425 |
-
rel = f"{path}/{name}".replace("//", "/").strip("/") if path else name
|
| 426 |
-
return JSONResponse({"message": f"Folder '{name}' created.", "path": rel})
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
@app.post("/create_file")
|
| 430 |
-
def create_file(
|
| 431 |
-
path: str = Form(""),
|
| 432 |
-
name: str = Form(...),
|
| 433 |
-
effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
|
| 434 |
-
):
|
| 435 |
-
user_id, _ = effective
|
| 436 |
-
path = _strip_storage_path(path)
|
| 437 |
-
if path and ".." in path:
|
| 438 |
-
return JSONResponse({"error": "Invalid path."}, status_code=400)
|
| 439 |
-
tree = _get_vfs_tree_clean(user_id)
|
| 440 |
-
if path and not tree_has_folder(tree, path):
|
| 441 |
-
return JSONResponse({"error": f"Folder '{path}' does not exist."}, status_code=400)
|
| 442 |
-
filename = name if "." in name else f"{name}.txt"
|
| 443 |
-
if "/" in filename.replace("\\", "/") or ".." in filename:
|
| 444 |
-
return JSONResponse({"error": "Invalid file name."}, status_code=400)
|
| 445 |
-
vfs_set_tree(user_id, tree_add_file(tree, path, filename))
|
| 446 |
-
rel_path = f"{path}/{filename}".replace("//", "/").strip("/") if path else filename
|
| 447 |
-
user_document_upsert(user_id, rel_path, "", filename)
|
| 448 |
-
return JSONResponse({"message": f"File '{filename}' created.", "path": rel_path})
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
def _safe_user_document_upsert(user_id: str, path: str, content: str, original_filename: str) -> str | None:
|
| 452 |
-
"""Best-effort cache write; should not block ingestion/query pipeline."""
|
| 453 |
-
try:
|
| 454 |
-
user_document_upsert(user_id, path, content, original_filename)
|
| 455 |
-
return None
|
| 456 |
-
except Exception as e:
|
| 457 |
-
return f"user_documents cache write skipped: {str(e)}"
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
@app.post("/upload_note")
|
| 461 |
-
def upload_note(
|
| 462 |
-
path: str = Form(""),
|
| 463 |
-
file: UploadFile = File(...),
|
| 464 |
-
effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
|
| 465 |
-
):
|
| 466 |
-
user_id, _ = effective
|
| 467 |
-
path = _strip_storage_path(path)
|
| 468 |
-
if path and ".." in path:
|
| 469 |
-
return JSONResponse({"error": "Invalid path."}, status_code=400)
|
| 470 |
-
tree = _get_vfs_tree_clean(user_id)
|
| 471 |
-
if path and not tree_has_folder(tree, path):
|
| 472 |
-
return JSONResponse({"error": f"Folder '{path}' does not exist."}, status_code=400)
|
| 473 |
-
|
| 474 |
-
raw_name = (file.filename or "upload").replace("\\", "/").split("/")[-1]
|
| 475 |
-
if ".." in raw_name or not raw_name.strip():
|
| 476 |
-
return JSONResponse({"error": "Invalid file name."}, status_code=400)
|
| 477 |
-
|
| 478 |
-
file_content = file.file.read()
|
| 479 |
-
rel_path = _strip_storage_path(
|
| 480 |
-
(os.path.join(path, raw_name) if path else raw_name).replace("\\", "/"),
|
| 481 |
-
)
|
| 482 |
-
vfs_set_tree(user_id, tree_add_file(tree, path, raw_name))
|
| 483 |
-
|
| 484 |
-
is_pdf = raw_name.lower().endswith(".pdf")
|
| 485 |
-
ext = os.path.splitext(raw_name)[1].lower()
|
| 486 |
-
is_image = ext in (".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".gif", ".webp")
|
| 487 |
-
|
| 488 |
-
try:
|
| 489 |
-
warnings: list[str] = []
|
| 490 |
-
if is_pdf:
|
| 491 |
-
text, v_err = llm_pipeline.transcribe_document_bytes(file_content, "application/pdf")
|
| 492 |
-
if not (text or "").strip():
|
| 493 |
-
from backend.extract_api import extract_text_from_pdf_bytes
|
| 494 |
-
text = extract_text_from_pdf_bytes(file_content)
|
| 495 |
-
v_err = v_err or "used_pdf_parser_fallback"
|
| 496 |
-
rel_path_txt = rel_path.replace(os.path.splitext(rel_path)[1], ".txt")
|
| 497 |
-
w = _safe_user_document_upsert(user_id, rel_path_txt, text, raw_name)
|
| 498 |
-
if w:
|
| 499 |
-
warnings.append(w)
|
| 500 |
-
ingest_result = ingest_text_for_path(user_id, rel_path, raw_name, text or "")
|
| 501 |
-
return JSONResponse({
|
| 502 |
-
"message": f"File '{raw_name}' uploaded and processed successfully.",
|
| 503 |
-
"path": rel_path,
|
| 504 |
-
"vision_note": v_err,
|
| 505 |
-
"ingestion": ingest_result,
|
| 506 |
-
"warnings": warnings,
|
| 507 |
-
})
|
| 508 |
-
if is_image:
|
| 509 |
-
mime = {
|
| 510 |
-
".jpg": "image/jpeg",
|
| 511 |
-
".jpeg": "image/jpeg",
|
| 512 |
-
".png": "image/png",
|
| 513 |
-
".webp": "image/webp",
|
| 514 |
-
".gif": "image/gif",
|
| 515 |
-
".bmp": "image/bmp",
|
| 516 |
-
".tiff": "image/tiff",
|
| 517 |
-
}.get(ext, "image/jpeg")
|
| 518 |
-
text, v_err = llm_pipeline.transcribe_handwritten_image(file_content, mime)
|
| 519 |
-
if not (text or "").strip():
|
| 520 |
-
from backend.extract_api import extract_text_from_image_bytes
|
| 521 |
-
|
| 522 |
-
text = extract_text_from_image_bytes(file_content)
|
| 523 |
-
v_err = v_err or "used_tesseract_fallback"
|
| 524 |
-
base_name = os.path.splitext(raw_name)[0] + ".txt"
|
| 525 |
-
rel_txt = (os.path.join(path, base_name) if path else base_name).replace("\\", "/")
|
| 526 |
-
w = _safe_user_document_upsert(user_id, rel_txt, text or "", raw_name)
|
| 527 |
-
if w:
|
| 528 |
-
warnings.append(w)
|
| 529 |
-
ingest_result = ingest_text_for_path(user_id, rel_txt, raw_name, text or "")
|
| 530 |
-
return JSONResponse({
|
| 531 |
-
"message": f"File '{raw_name}' uploaded and processed successfully.",
|
| 532 |
-
"path": rel_path,
|
| 533 |
-
"vision_note": v_err,
|
| 534 |
-
"ingestion": ingest_result,
|
| 535 |
-
"warnings": warnings,
|
| 536 |
-
})
|
| 537 |
-
if not is_pdf and not is_image:
|
| 538 |
-
text_plain = ""
|
| 539 |
-
low = raw_name.lower()
|
| 540 |
-
if low.endswith((".txt", ".md", ".csv", ".json", ".log")):
|
| 541 |
-
try:
|
| 542 |
-
text_plain = file_content.decode("utf-8")
|
| 543 |
-
except UnicodeDecodeError:
|
| 544 |
-
text_plain = file_content.decode("utf-8", errors="replace")
|
| 545 |
-
if (text_plain or "").strip():
|
| 546 |
-
w = _safe_user_document_upsert(user_id, rel_path, text_plain, raw_name)
|
| 547 |
-
if w:
|
| 548 |
-
warnings.append(w)
|
| 549 |
-
ingest_result = ingest_text_for_path(user_id, rel_path, raw_name, text_plain)
|
| 550 |
-
return JSONResponse({
|
| 551 |
-
"message": f"File '{raw_name}' uploaded and processed successfully.",
|
| 552 |
-
"path": rel_path,
|
| 553 |
-
"ingestion": ingest_result,
|
| 554 |
-
"warnings": warnings,
|
| 555 |
-
})
|
| 556 |
-
return JSONResponse({
|
| 557 |
-
"message": f"File '{raw_name}' recorded (no server-side binary stored).",
|
| 558 |
-
"path": rel_path,
|
| 559 |
-
"warnings": warnings,
|
| 560 |
-
})
|
| 561 |
-
except Exception as e:
|
| 562 |
-
return JSONResponse({
|
| 563 |
-
"message": f"File '{raw_name}' recorded but processing failed: {str(e)}",
|
| 564 |
-
"path": rel_path,
|
| 565 |
-
}, status_code=500)
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
@app.post("/chat/upload_ephemeral")
|
| 569 |
-
def chat_upload_ephemeral(
|
| 570 |
-
chat_session_id: str = Form(...),
|
| 571 |
-
file: UploadFile = File(...),
|
| 572 |
-
effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
|
| 573 |
-
):
|
| 574 |
-
user_id, _ = effective
|
| 575 |
-
sid = (chat_session_id or "").strip()
|
| 576 |
-
if not sid:
|
| 577 |
-
return JSONResponse({"error": "chat_session_id is required."}, status_code=400)
|
| 578 |
-
raw_name = (file.filename or "upload").replace("\\", "/").split("/")[-1]
|
| 579 |
-
if ".." in raw_name or not raw_name.strip():
|
| 580 |
-
return JSONResponse({"error": "Invalid file name."}, status_code=400)
|
| 581 |
-
data = file.file.read()
|
| 582 |
-
ext = os.path.splitext(raw_name)[1].lower()
|
| 583 |
-
is_pdf = ext == ".pdf"
|
| 584 |
-
is_image = ext in (".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".gif", ".webp")
|
| 585 |
-
text = ""
|
| 586 |
-
source = ""
|
| 587 |
-
if is_pdf:
|
| 588 |
-
text, source = llm_pipeline.transcribe_document_bytes(data, "application/pdf")
|
| 589 |
-
if not (text or "").strip():
|
| 590 |
-
from backend.extract_api import extract_text_from_pdf_bytes
|
| 591 |
-
text = extract_text_from_pdf_bytes(data)
|
| 592 |
-
source = source or "used_pdf_parser_fallback"
|
| 593 |
-
elif is_image:
|
| 594 |
-
mime = {
|
| 595 |
-
".jpg": "image/jpeg",
|
| 596 |
-
".jpeg": "image/jpeg",
|
| 597 |
-
".png": "image/png",
|
| 598 |
-
".webp": "image/webp",
|
| 599 |
-
".gif": "image/gif",
|
| 600 |
-
".bmp": "image/bmp",
|
| 601 |
-
".tiff": "image/tiff",
|
| 602 |
-
}.get(ext, "image/jpeg")
|
| 603 |
-
text, source = llm_pipeline.transcribe_handwritten_image(data, mime)
|
| 604 |
-
if not (text or "").strip():
|
| 605 |
-
from backend.extract_api import extract_text_from_image_bytes
|
| 606 |
-
text = extract_text_from_image_bytes(data)
|
| 607 |
-
source = source or "used_tesseract_fallback"
|
| 608 |
-
else:
|
| 609 |
-
if raw_name.lower().endswith((".txt", ".md", ".csv", ".json", ".log")):
|
| 610 |
-
try:
|
| 611 |
-
text = data.decode("utf-8")
|
| 612 |
-
except UnicodeDecodeError:
|
| 613 |
-
text = data.decode("utf-8", errors="replace")
|
| 614 |
-
source = "plain_text"
|
| 615 |
-
if not (text or "").strip():
|
| 616 |
-
return JSONResponse({"error": "No extractable text found in this file."}, status_code=400)
|
| 617 |
-
_chat_cache_add(
|
| 618 |
-
user_id,
|
| 619 |
-
sid,
|
| 620 |
-
{
|
| 621 |
-
"name": raw_name,
|
| 622 |
-
"text": (text or "").strip()[:120000],
|
| 623 |
-
"source": source or "",
|
| 624 |
-
"uploaded_at": datetime.now().isoformat(),
|
| 625 |
-
},
|
| 626 |
-
)
|
| 627 |
-
return JSONResponse(
|
| 628 |
-
{
|
| 629 |
-
"message": f"Cached '{raw_name}' for this chat session.",
|
| 630 |
-
"chat_session_id": sid,
|
| 631 |
-
"cached_files_count": len(_chat_cache_items(user_id, sid)),
|
| 632 |
-
"text_chars": len((text or "").strip()),
|
| 633 |
-
"extractor_note": source or "",
|
| 634 |
-
}
|
| 635 |
-
)
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
@app.post("/chat/session/clear")
|
| 639 |
-
def clear_chat_session_cache(
|
| 640 |
-
chat_session_id: str = Form(...),
|
| 641 |
-
effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
|
| 642 |
-
):
|
| 643 |
-
user_id, _ = effective
|
| 644 |
-
sid = (chat_session_id or "").strip()
|
| 645 |
-
if not sid:
|
| 646 |
-
return JSONResponse({"error": "chat_session_id is required."}, status_code=400)
|
| 647 |
-
deleted = _chat_cache_clear(user_id, sid)
|
| 648 |
-
return JSONResponse({"message": "Chat cache cleared.", "deleted_files": deleted})
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
@app.delete("/notes")
|
| 652 |
-
def delete_notes(
|
| 653 |
-
file: str | None = None,
|
| 654 |
-
files: str | None = None,
|
| 655 |
-
effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
|
| 656 |
-
):
|
| 657 |
-
"""
|
| 658 |
-
Delete the authenticated user's note chunks from ChromaDB.
|
| 659 |
-
- No query params: delete entire collection (user_{user_id}_notes).
|
| 660 |
-
- file=<path>: delete only chunks for that path.
|
| 661 |
-
- files=<path1>,<path2>: delete only chunks for those paths.
|
| 662 |
-
"""
|
| 663 |
-
user_id, _ = effective
|
| 664 |
-
if file:
|
| 665 |
-
paths = [p.strip() for p in [file] if p and p.strip()]
|
| 666 |
-
elif files:
|
| 667 |
-
paths = [p.strip() for p in files.split(",") if p and p.strip()]
|
| 668 |
-
else:
|
| 669 |
-
paths = None
|
| 670 |
-
if paths is not None:
|
| 671 |
-
if not paths:
|
| 672 |
-
return JSONResponse({"error": "No paths provided."}, status_code=400)
|
| 673 |
-
for p in paths:
|
| 674 |
-
if ".." in p or p.startswith("/"):
|
| 675 |
-
return JSONResponse({"error": "Invalid path."}, status_code=400)
|
| 676 |
-
paths = [_strip_storage_path(p) for p in paths]
|
| 677 |
-
deleted = delete_user_notes_by_paths(user_id, paths)
|
| 678 |
-
return JSONResponse({"message": f"Deleted {deleted} chunk(s) for the given file(s).", "deleted_count": deleted})
|
| 679 |
-
deleted_notes = delete_user_notes_collection(user_id)
|
| 680 |
-
deleted_vfs = delete_user_vfs_collection(user_id)
|
| 681 |
-
user_document_delete_many(user_id, path_filter=None)
|
| 682 |
-
return JSONResponse({
|
| 683 |
-
"message": "All notes data deleted." if deleted_notes else "No notes collection found.",
|
| 684 |
-
"deleted_notes": deleted_notes,
|
| 685 |
-
"deleted_vfs": deleted_vfs,
|
| 686 |
-
})
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
@app.get("/list_tree")
|
| 690 |
-
def list_tree(effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None):
|
| 691 |
-
user_id, _ = effective
|
| 692 |
-
return {"tree": _get_vfs_tree_clean(user_id)}
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
@app.post("/query_folder")
|
| 698 |
-
def query_notes(
|
| 699 |
-
subject: str = Form(""),
|
| 700 |
-
courses: str = Form(""),
|
| 701 |
-
query: str = Form(...),
|
| 702 |
-
highlight: str = Form(""),
|
| 703 |
-
opened_file_path: str = Form(""),
|
| 704 |
-
course_path: str = Form(""),
|
| 705 |
-
include_course_context: bool = Form(True),
|
| 706 |
-
chat_session_id: str = Form(""),
|
| 707 |
-
use_course_notes: bool = Form(False),
|
| 708 |
-
effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
|
| 709 |
-
):
|
| 710 |
-
user_id, _ = effective
|
| 711 |
-
q = (query or "").strip()
|
| 712 |
-
if not q:
|
| 713 |
-
return JSONResponse({"error": "Query is empty.", "answer": "", "source_documents": []}, status_code=400)
|
| 714 |
-
tree = _get_vfs_tree_clean(user_id)
|
| 715 |
-
all_paths = [p.replace("\\", "/") for p in flatten_file_paths(tree)]
|
| 716 |
-
all_set = set(all_paths)
|
| 717 |
-
opened = _strip_storage_path(opened_file_path or "")
|
| 718 |
-
course = _strip_storage_path(course_path or "")
|
| 719 |
-
if not course and opened:
|
| 720 |
-
course = opened.split("/", 1)[0] if "/" in opened else opened
|
| 721 |
-
if course and "/" in course:
|
| 722 |
-
course = course.split("/", 1)[0]
|
| 723 |
-
ephemeral = _chat_cache_items(user_id, chat_session_id)
|
| 724 |
-
|
| 725 |
-
hl = (highlight or "").strip()
|
| 726 |
-
full_q = f'Regarding this selection:\n"""{hl}"""\n\n{q}' if hl else q
|
| 727 |
-
try:
|
| 728 |
-
col = get_user_collection(user_id)
|
| 729 |
-
embed = _get_query_embedder()
|
| 730 |
-
q_emb = embed.encode([full_q]).tolist()[0]
|
| 731 |
-
|
| 732 |
-
def _query_path_candidates(path: str) -> list[str]:
|
| 733 |
-
"""For image/text-extracted notes, also try the .txt twin path."""
|
| 734 |
-
p = _strip_storage_path(path or "")
|
| 735 |
-
if not p:
|
| 736 |
-
return []
|
| 737 |
-
out = [p]
|
| 738 |
-
stem, ext = os.path.splitext(p)
|
| 739 |
-
if ext and ext.lower() != ".txt":
|
| 740 |
-
out.append(stem + ".txt")
|
| 741 |
-
# preserve order, dedupe
|
| 742 |
-
return list(dict.fromkeys(out))
|
| 743 |
-
|
| 744 |
-
def _cos(a: list[float], b: list[float]) -> float:
|
| 745 |
-
dot = sum((x * y) for x, y in zip(a, b))
|
| 746 |
-
na = (sum((x * x) for x in a) or 1e-9) ** 0.5
|
| 747 |
-
nb = (sum((y * y) for y in b) or 1e-9) ** 0.5
|
| 748 |
-
return float(dot / (na * nb))
|
| 749 |
-
|
| 750 |
-
def _split_text(t: str, size: int = 900, overlap: int = 120) -> list[str]:
|
| 751 |
-
tx = (t or "").strip()
|
| 752 |
-
if not tx:
|
| 753 |
-
return []
|
| 754 |
-
out: list[str] = []
|
| 755 |
-
i = 0
|
| 756 |
-
n = len(tx)
|
| 757 |
-
while i < n:
|
| 758 |
-
out.append(tx[i : i + size])
|
| 759 |
-
i += max(1, size - overlap)
|
| 760 |
-
return out
|
| 761 |
-
|
| 762 |
-
def _query_path_docs(path: str, n_results: int = 5) -> list[dict]:
|
| 763 |
-
out = []
|
| 764 |
-
seen_local: set[str] = set()
|
| 765 |
-
for p in _query_path_candidates(path):
|
| 766 |
-
res = col.query(
|
| 767 |
-
query_embeddings=[q_emb],
|
| 768 |
-
n_results=n_results,
|
| 769 |
-
where={"path": p},
|
| 770 |
-
include=["documents", "metadatas", "distances"],
|
| 771 |
-
)
|
| 772 |
-
ids = (res.get("ids") or [[]])[0] if isinstance(res.get("ids"), list) else []
|
| 773 |
-
docs = (res.get("documents") or [[]])[0] if isinstance(res.get("documents"), list) else []
|
| 774 |
-
metas = (res.get("metadatas") or [[]])[0] if isinstance(res.get("metadatas"), list) else []
|
| 775 |
-
dists = (res.get("distances") or [[]])[0] if isinstance(res.get("distances"), list) else []
|
| 776 |
-
for i, cid in enumerate(ids):
|
| 777 |
-
key = f"{p}|{cid}"
|
| 778 |
-
if key in seen_local:
|
| 779 |
-
continue
|
| 780 |
-
seen_local.add(key)
|
| 781 |
-
content = (docs[i] if i < len(docs) else "") or ""
|
| 782 |
-
if not content.strip():
|
| 783 |
-
continue
|
| 784 |
-
md = metas[i] if i < len(metas) and isinstance(metas[i], dict) else {}
|
| 785 |
-
dist = float(dists[i]) if i < len(dists) and dists[i] is not None else 2.0
|
| 786 |
-
score = 1.0 - dist
|
| 787 |
-
out.append({"id": cid, "content": content, "metadata": md, "_score": score})
|
| 788 |
-
out.sort(key=lambda d: d.get("_score", -9), reverse=True)
|
| 789 |
-
return out
|
| 790 |
-
|
| 791 |
-
# Stage 1: ephemeral chat uploads (highest priority)
|
| 792 |
-
eph_docs: list[dict] = []
|
| 793 |
-
for i, it in enumerate(ephemeral):
|
| 794 |
-
et = str((it or {}).get("text") or "").strip()
|
| 795 |
-
if not et:
|
| 796 |
-
continue
|
| 797 |
-
chunks = _split_text(et, size=900, overlap=140)[:24]
|
| 798 |
-
if not chunks:
|
| 799 |
-
continue
|
| 800 |
-
c_embs = embed.encode(chunks).tolist()
|
| 801 |
-
ranked = sorted(
|
| 802 |
-
[(_cos(q_emb, ce), ch) for ce, ch in zip(c_embs, chunks)],
|
| 803 |
-
key=lambda x: x[0],
|
| 804 |
-
reverse=True,
|
| 805 |
-
)[:3]
|
| 806 |
-
for j, (sc, ch) in enumerate(ranked):
|
| 807 |
-
eph_docs.append(
|
| 808 |
-
{
|
| 809 |
-
"id": f"ephemeral|{i}|{j}",
|
| 810 |
-
"content": ch,
|
| 811 |
-
"metadata": {
|
| 812 |
-
"path": f"[chat-upload] {(it or {}).get('name') or 'file'}",
|
| 813 |
-
"source_file": (it or {}).get("name") or "chat-upload",
|
| 814 |
-
"ephemeral_chat_upload": 1,
|
| 815 |
-
},
|
| 816 |
-
"_score": float(sc),
|
| 817 |
-
}
|
| 818 |
-
)
|
| 819 |
-
eph_docs.sort(key=lambda d: d.get("_score", -9), reverse=True)
|
| 820 |
-
eph_best = eph_docs[0]["_score"] if eph_docs else -1.0
|
| 821 |
-
|
| 822 |
-
# Stage 2: opened file
|
| 823 |
-
open_docs: list[dict] = []
|
| 824 |
-
if opened and opened in all_set:
|
| 825 |
-
open_docs = _query_path_docs(opened, n_results=6)
|
| 826 |
-
open_best = open_docs[0]["_score"] if open_docs else -1.0
|
| 827 |
-
|
| 828 |
-
# Stage 3: same course files (excluding opened)
|
| 829 |
-
course_docs: list[dict] = []
|
| 830 |
-
if include_course_context and course:
|
| 831 |
-
prefix = f"{course}/"
|
| 832 |
-
course_paths = [p for p in all_paths if p != opened and p.startswith(prefix)]
|
| 833 |
-
for p in course_paths[:18]:
|
| 834 |
-
course_docs.extend(_query_path_docs(p, n_results=2))
|
| 835 |
-
course_docs.sort(key=lambda d: d.get("_score", -9), reverse=True)
|
| 836 |
-
course_best = course_docs[0]["_score"] if course_docs else -1.0
|
| 837 |
-
|
| 838 |
-
# Sequence policy:
|
| 839 |
-
# 1) use ephemeral if relevant enough
|
| 840 |
-
# 2) otherwise opened file
|
| 841 |
-
# 3) otherwise same-course files
|
| 842 |
-
selected: list[dict] = []
|
| 843 |
-
stage = "ephemeral"
|
| 844 |
-
if eph_docs and eph_best >= 0.32:
|
| 845 |
-
selected = eph_docs[:8]
|
| 846 |
-
stage = "ephemeral"
|
| 847 |
-
elif open_docs and open_best >= 0.05:
|
| 848 |
-
selected = open_docs[:8]
|
| 849 |
-
stage = "opened"
|
| 850 |
-
elif course_docs and course_best >= 0.02:
|
| 851 |
-
selected = course_docs[:8]
|
| 852 |
-
stage = "course"
|
| 853 |
-
else:
|
| 854 |
-
# Smart fallback: best available source by embedding score.
|
| 855 |
-
cands = [
|
| 856 |
-
("ephemeral", eph_best, eph_docs),
|
| 857 |
-
("opened", open_best, open_docs),
|
| 858 |
-
("course", course_best, course_docs),
|
| 859 |
-
]
|
| 860 |
-
cands.sort(key=lambda x: x[1], reverse=True)
|
| 861 |
-
stage, _best, dd = cands[0]
|
| 862 |
-
selected = (dd or [])[:8]
|
| 863 |
-
|
| 864 |
-
if not selected:
|
| 865 |
-
return JSONResponse(
|
| 866 |
-
{
|
| 867 |
-
"error": "No relevant text found in chat uploads, open file, or course notes.",
|
| 868 |
-
"query": q,
|
| 869 |
-
"answer": "",
|
| 870 |
-
"source_documents": [],
|
| 871 |
-
},
|
| 872 |
-
status_code=400,
|
| 873 |
-
)
|
| 874 |
-
|
| 875 |
-
context = "\n\n".join(
|
| 876 |
-
[
|
| 877 |
-
f"[{(d.get('metadata') or {}).get('path') or 'chunk'}]\n{(d.get('content') or '')[:1200]}"
|
| 878 |
-
for d in selected
|
| 879 |
-
if (d.get("content") or "").strip()
|
| 880 |
-
]
|
| 881 |
-
)
|
| 882 |
-
answer, err = llm_pipeline.sarvam_rag_answer(full_q, context)
|
| 883 |
-
if err:
|
| 884 |
-
return JSONResponse(
|
| 885 |
-
{
|
| 886 |
-
"error": err,
|
| 887 |
-
"query": q,
|
| 888 |
-
"answer": "",
|
| 889 |
-
"source_documents": [],
|
| 890 |
-
},
|
| 891 |
-
status_code=503,
|
| 892 |
-
)
|
| 893 |
-
docs_out = [{k: v for k, v in d.items() if k != "_score"} for d in selected]
|
| 894 |
-
return JSONResponse(
|
| 895 |
-
{
|
| 896 |
-
"query": q,
|
| 897 |
-
"answer": answer or "",
|
| 898 |
-
"source_documents": docs_out,
|
| 899 |
-
"grounded_on_path": opened,
|
| 900 |
-
"ephemeral_files_used": len(ephemeral),
|
| 901 |
-
"selection_stage": stage,
|
| 902 |
-
"score_ephemeral_best": round(float(eph_best), 4),
|
| 903 |
-
"score_opened_best": round(float(open_best), 4),
|
| 904 |
-
"score_course_best": round(float(course_best), 4),
|
| 905 |
-
}
|
| 906 |
-
)
|
| 907 |
-
except Exception as e:
|
| 908 |
-
return JSONResponse(
|
| 909 |
-
{
|
| 910 |
-
"error": f"Query failed: {str(e)}",
|
| 911 |
-
"query": q,
|
| 912 |
-
"answer": "",
|
| 913 |
-
"source_documents": [],
|
| 914 |
-
},
|
| 915 |
-
status_code=500,
|
| 916 |
-
)
|
| 917 |
-
|
| 918 |
-
|
| 919 |
-
@app.get("/file_meta")
|
| 920 |
-
def get_file_meta_route(
|
| 921 |
-
effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
|
| 922 |
-
):
|
| 923 |
-
user_id, _ = effective
|
| 924 |
-
return {"meta": load_file_meta(user_id)}
|
| 925 |
-
|
| 926 |
-
|
| 927 |
-
@app.post("/file_meta")
|
| 928 |
-
def post_file_meta(
|
| 929 |
-
path: str = Form(...),
|
| 930 |
-
is_primary_authority: str = Form("false"),
|
| 931 |
-
doc_type: str = Form(""),
|
| 932 |
-
related_paths: str = Form(""),
|
| 933 |
-
effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
|
| 934 |
-
):
|
| 935 |
-
user_id, _ = effective
|
| 936 |
-
path = _strip_storage_path(path)
|
| 937 |
-
primary = str(is_primary_authority).lower() in ("1", "true", "yes", "on")
|
| 938 |
-
rel_list = [
|
| 939 |
-
_strip_storage_path(x.strip().replace("\\", "/"))
|
| 940 |
-
for x in related_paths.split(",")
|
| 941 |
-
if x.strip()
|
| 942 |
-
]
|
| 943 |
-
entry = set_entry(
|
| 944 |
-
user_id,
|
| 945 |
-
path,
|
| 946 |
-
is_primary_authority=primary,
|
| 947 |
-
doc_type=(doc_type or "other"),
|
| 948 |
-
related_paths=rel_list,
|
| 949 |
-
)
|
| 950 |
-
n = refresh_metadata_for_paths(user_id, chunk_paths_for_file(path))
|
| 951 |
-
return JSONResponse({"path": path, "entry": entry, "chunks_updated": n})
|
| 952 |
-
|
| 953 |
-
|
| 954 |
-
def _doc_text_for_virtual_path(user_id: str, rel_path: str) -> str:
|
| 955 |
-
"""Resolve extracted/stored text for a virtual file path."""
|
| 956 |
-
p = _strip_storage_path(rel_path or "")
|
| 957 |
-
if not p:
|
| 958 |
-
return ""
|
| 959 |
-
direct = user_document_get_content(user_id, p)
|
| 960 |
-
if (direct or "").strip():
|
| 961 |
-
return (direct or "").strip()
|
| 962 |
-
stem, ext = os.path.splitext(p)
|
| 963 |
-
if ext.lower() != ".txt":
|
| 964 |
-
txt = user_document_get_content(user_id, stem + ".txt")
|
| 965 |
-
if (txt or "").strip():
|
| 966 |
-
return (txt or "").strip()
|
| 967 |
-
return ""
|
| 968 |
-
|
| 969 |
-
|
| 970 |
-
def _study_text_for_path(user_id: str, rel_path: str) -> str:
|
| 971 |
-
"""Prefer Chroma chunk text (same as RAG), fall back to user_documents."""
|
| 972 |
-
p = _strip_storage_path(rel_path or "")
|
| 973 |
-
if not p:
|
| 974 |
-
return ""
|
| 975 |
-
chunk = (user_notes_concat_text_for_path(user_id, p) or "").strip()
|
| 976 |
-
if chunk:
|
| 977 |
-
return chunk
|
| 978 |
-
return (_doc_text_for_virtual_path(user_id, p) or "").strip()
|
| 979 |
-
|
| 980 |
-
|
| 981 |
-
def _build_study_scope_context(
|
| 982 |
-
user_id: str,
|
| 983 |
-
opened_file_path: str,
|
| 984 |
-
course_path: str,
|
| 985 |
-
focus_query: str,
|
| 986 |
-
include_course_context: bool,
|
| 987 |
-
) -> tuple[str | None, str | None]:
|
| 988 |
-
"""Return context strictly from opened file and optionally same course folder."""
|
| 989 |
-
open_rel = _strip_storage_path(opened_file_path or "")
|
| 990 |
-
if not open_rel:
|
| 991 |
-
return None, "Open a file first. Study generation uses the active file context."
|
| 992 |
-
|
| 993 |
-
tree = _get_vfs_tree_clean(user_id)
|
| 994 |
-
all_paths = [p.replace("\\", "/") for p in flatten_file_paths(tree)]
|
| 995 |
-
all_set = set(all_paths)
|
| 996 |
-
if open_rel not in all_set:
|
| 997 |
-
return None, f"Active file '{open_rel}' was not found in your notes."
|
| 998 |
-
|
| 999 |
-
root_course = _strip_storage_path(course_path or "")
|
| 1000 |
-
if not root_course:
|
| 1001 |
-
root_course = open_rel.split("/", 1)[0] if "/" in open_rel else open_rel
|
| 1002 |
-
# Root course is only a top-level folder scope, never a file path.
|
| 1003 |
-
root_course = root_course.split("/", 1)[0] if root_course else ""
|
| 1004 |
-
|
| 1005 |
-
open_text = (_study_text_for_path(user_id, open_rel) or "").strip()
|
| 1006 |
-
if not open_text:
|
| 1007 |
-
return None, (
|
| 1008 |
-
f"No extracted text or chunks found for '{open_rel}'. "
|
| 1009 |
-
"Re-upload the file or wait for ingestion to finish."
|
| 1010 |
-
)
|
| 1011 |
-
|
| 1012 |
-
focus = (focus_query or "").strip() or "key ideas for exam"
|
| 1013 |
-
parts = [
|
| 1014 |
-
f"Focus: {focus}",
|
| 1015 |
-
f"Active course folder: {root_course or '(root)'}",
|
| 1016 |
-
f"Primary file: {open_rel}",
|
| 1017 |
-
"",
|
| 1018 |
-
"--- PRIMARY FILE CONTENT ---",
|
| 1019 |
-
open_text[:35000],
|
| 1020 |
-
]
|
| 1021 |
-
|
| 1022 |
-
if include_course_context and root_course:
|
| 1023 |
-
prefix = root_course + "/"
|
| 1024 |
-
extra_paths = [p for p in all_paths if p != open_rel and (p == root_course or p.startswith(prefix))]
|
| 1025 |
-
if extra_paths:
|
| 1026 |
-
budget = 25000
|
| 1027 |
-
extras: list[str] = []
|
| 1028 |
-
for p in extra_paths:
|
| 1029 |
-
if budget <= 0:
|
| 1030 |
-
break
|
| 1031 |
-
t = _study_text_for_path(user_id, p)
|
| 1032 |
-
if not t:
|
| 1033 |
-
continue
|
| 1034 |
-
chunk = t[: min(len(t), 3500, budget)]
|
| 1035 |
-
if not chunk.strip():
|
| 1036 |
-
continue
|
| 1037 |
-
extras.append(f"--- COURSE SUPPORTING FILE: {p} ---\n{chunk}")
|
| 1038 |
-
budget -= len(chunk)
|
| 1039 |
-
if extras:
|
| 1040 |
-
parts.append("")
|
| 1041 |
-
parts.append("--- OPTIONAL SAME-COURSE SUPPORT ---")
|
| 1042 |
-
parts.append("\n\n".join(extras))
|
| 1043 |
-
|
| 1044 |
-
return "\n".join(parts)[:60000], None
|
| 1045 |
-
|
| 1046 |
|
| 1047 |
-
|
| 1048 |
-
|
| 1049 |
-
task: str = Form("flashcards"),
|
| 1050 |
-
count: int = Form(5),
|
| 1051 |
-
courses: str = Form(""),
|
| 1052 |
-
focus_query: str = Form("key ideas for exam"),
|
| 1053 |
-
opened_file_path: str = Form(""),
|
| 1054 |
-
course_path: str = Form(""),
|
| 1055 |
-
include_course_context: bool = Form(True),
|
| 1056 |
-
effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
|
| 1057 |
-
):
|
| 1058 |
-
_uid, _ = effective
|
| 1059 |
-
course_list = [c.strip() for c in courses.split(",") if c.strip()]
|
| 1060 |
-
focus = (focus_query or "").strip() or "key ideas for exam"
|
| 1061 |
-
scope = ", ".join(course_list) if course_list else "general"
|
| 1062 |
-
ctx, cerr = _build_study_scope_context(
|
| 1063 |
-
_uid,
|
| 1064 |
-
opened_file_path,
|
| 1065 |
-
course_path,
|
| 1066 |
-
focus,
|
| 1067 |
-
include_course_context,
|
| 1068 |
-
)
|
| 1069 |
-
if cerr:
|
| 1070 |
-
return JSONResponse({"error": cerr, "scope": scope}, status_code=400)
|
| 1071 |
-
data, err = llm_pipeline.cheap_study_json(ctx, task, max(1, min(count, 30)))
|
| 1072 |
-
if err:
|
| 1073 |
-
return JSONResponse({"error": err}, status_code=503)
|
| 1074 |
-
return JSONResponse(
|
| 1075 |
-
{
|
| 1076 |
-
"task": task,
|
| 1077 |
-
"items": data,
|
| 1078 |
-
"grounded_on_path": _strip_storage_path(opened_file_path or ""),
|
| 1079 |
-
"context_chars": len(ctx or ""),
|
| 1080 |
-
}
|
| 1081 |
-
)
|
| 1082 |
|
| 1083 |
|
| 1084 |
-
@app.
|
| 1085 |
-
def
|
| 1086 |
-
|
| 1087 |
-
|
| 1088 |
-
opened_file_path: str = Form(""),
|
| 1089 |
-
course_path: str = Form(""),
|
| 1090 |
-
include_course_context: bool = Form(True),
|
| 1091 |
-
effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
|
| 1092 |
-
):
|
| 1093 |
-
_uid, _ = effective
|
| 1094 |
-
course_list = [c.strip() for c in courses.split(",") if c.strip()]
|
| 1095 |
-
focus = (focus_query or "").strip() or "main concepts"
|
| 1096 |
-
scope = ", ".join(course_list) if course_list else "general"
|
| 1097 |
-
ctx, cerr = _build_study_scope_context(
|
| 1098 |
-
_uid,
|
| 1099 |
-
opened_file_path,
|
| 1100 |
-
course_path,
|
| 1101 |
-
focus,
|
| 1102 |
-
include_course_context,
|
| 1103 |
-
)
|
| 1104 |
-
if cerr:
|
| 1105 |
-
return JSONResponse({"error": cerr, "scope": scope}, status_code=400)
|
| 1106 |
-
summary_text, err = llm_pipeline.topic_summary(ctx)
|
| 1107 |
-
if err:
|
| 1108 |
-
return JSONResponse({"error": err}, status_code=503)
|
| 1109 |
-
return JSONResponse(
|
| 1110 |
-
{
|
| 1111 |
-
"summary": summary_text,
|
| 1112 |
-
"grounded_on_path": _strip_storage_path(opened_file_path or ""),
|
| 1113 |
-
"context_chars": len(ctx or ""),
|
| 1114 |
-
}
|
| 1115 |
-
)
|
| 1116 |
|
| 1117 |
|
| 1118 |
-
@app.get("/
|
| 1119 |
-
def
|
| 1120 |
-
|
| 1121 |
-
):
|
| 1122 |
-
user_id, is_guest = effective
|
| 1123 |
-
connected = False
|
| 1124 |
-
if not is_guest:
|
| 1125 |
-
connected = bool(onenote_token_get(user_id))
|
| 1126 |
return {
|
| 1127 |
-
"
|
| 1128 |
-
"
|
| 1129 |
-
"
|
| 1130 |
-
"
|
|
|
|
|
|
|
| 1131 |
}
|
| 1132 |
|
| 1133 |
|
| 1134 |
-
@app.get("/integrations/onenote/auth_url")
|
| 1135 |
-
def onenote_auth_url(
|
| 1136 |
-
effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
|
| 1137 |
-
):
|
| 1138 |
-
user_id = _require_signed_in(effective)
|
| 1139 |
-
if not onenote_sync.is_configured():
|
| 1140 |
-
return JSONResponse(
|
| 1141 |
-
{"error": "Microsoft OAuth is not configured on server."},
|
| 1142 |
-
status_code=503,
|
| 1143 |
-
)
|
| 1144 |
-
state = str(uuid.uuid4())
|
| 1145 |
-
onenote_oauth_state_create(user_id, state, int(time.time()) + 600)
|
| 1146 |
-
return {"auth_url": onenote_sync.build_auth_url(state), "state": state}
|
| 1147 |
-
|
| 1148 |
-
|
| 1149 |
-
@app.get("/integrations/onenote/callback")
|
| 1150 |
-
def onenote_callback(code: str = "", state: str = "", error: str = "", error_description: str = ""):
|
| 1151 |
-
if error:
|
| 1152 |
-
msg = error_description or error
|
| 1153 |
-
html = (
|
| 1154 |
-
"<html><body><h3>OneNote connect failed</h3>"
|
| 1155 |
-
f"<p>{msg}</p><p>You can close this tab.</p></body></html>"
|
| 1156 |
-
)
|
| 1157 |
-
return HTMLResponse(content=html, status_code=400)
|
| 1158 |
-
if not code or not state:
|
| 1159 |
-
return HTMLResponse(
|
| 1160 |
-
content="<html><body><h3>Missing OAuth parameters.</h3><p>Close this tab.</p></body></html>",
|
| 1161 |
-
status_code=400,
|
| 1162 |
-
)
|
| 1163 |
-
user_id = onenote_oauth_state_pop_user_id(state)
|
| 1164 |
-
if not user_id:
|
| 1165 |
-
return HTMLResponse(
|
| 1166 |
-
content="<html><body><h3>OAuth state is invalid or expired.</h3><p>Restart connection.</p></body></html>",
|
| 1167 |
-
status_code=400,
|
| 1168 |
-
)
|
| 1169 |
-
try:
|
| 1170 |
-
token_payload = onenote_sync.exchange_code_for_token(code)
|
| 1171 |
-
onenote_token_upsert(user_id, token_payload)
|
| 1172 |
-
return HTMLResponse(
|
| 1173 |
-
content="<html><body><h3>OneNote connected successfully.</h3><p>You can close this tab and return to NoteScanner.</p></body></html>"
|
| 1174 |
-
)
|
| 1175 |
-
except Exception as e:
|
| 1176 |
-
return HTMLResponse(
|
| 1177 |
-
content=f"<html><body><h3>Token exchange failed.</h3><p>{str(e)}</p><p>Close this tab.</p></body></html>",
|
| 1178 |
-
status_code=500,
|
| 1179 |
-
)
|
| 1180 |
-
|
| 1181 |
-
|
| 1182 |
-
@app.post("/integrations/onenote/sync")
|
| 1183 |
-
def onenote_sync_route(
|
| 1184 |
-
max_pages: int = Form(25),
|
| 1185 |
-
effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
|
| 1186 |
-
):
|
| 1187 |
-
user_id = _require_signed_in(effective)
|
| 1188 |
-
if not onenote_sync.is_configured():
|
| 1189 |
-
return JSONResponse({"error": "Microsoft OAuth is not configured on server."}, status_code=503)
|
| 1190 |
-
try:
|
| 1191 |
-
out = onenote_sync.sync_onenote_pages_to_ingest(user_id, max_pages=max_pages)
|
| 1192 |
-
return JSONResponse({"message": "OneNote sync complete.", **out})
|
| 1193 |
-
except Exception as e:
|
| 1194 |
-
return JSONResponse({"error": str(e)}, status_code=500)
|
| 1195 |
-
|
| 1196 |
-
|
| 1197 |
if __name__ == "__main__":
|
| 1198 |
import uvicorn
|
|
|
|
| 1199 |
uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
|
| 1 |
+
"""NoteScanner API: app setup, error handling, CORS, and the route modules in backend/routes/."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from dotenv import load_dotenv
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
+
# Load .env before importing backend modules: some of them read settings at import time.
|
| 5 |
load_dotenv()
|
| 6 |
|
| 7 |
+
import logging
|
| 8 |
+
from contextlib import asynccontextmanager
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
+
from fastapi import FastAPI, HTTPException, Request
|
| 11 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 12 |
+
from fastapi.responses import JSONResponse
|
|
|
|
| 13 |
|
| 14 |
+
from backend import alerts, library, mailer, onenote_sync, preferences, rate_limit, reminders, settings
|
| 15 |
+
from backend.auth import SESSION_HEADER
|
| 16 |
+
from backend.routes import account, admin, chat, files, onenote, study
|
| 17 |
+
from backend.routes import library as library_routes
|
| 18 |
+
from backend.settings import MAX_CHAT_FILES_PER_SESSION, MAX_UPLOAD_MB, allowed_origins
|
| 19 |
|
| 20 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
| 21 |
+
logger = logging.getLogger("notescanner")
|
|
|
|
| 22 |
|
| 23 |
+
@asynccontextmanager
|
| 24 |
+
async def lifespan(_app: FastAPI):
|
| 25 |
+
reminders.start() # daily review emails (only when SMTP is set up)
|
| 26 |
+
library.start() # re-checks the shared course library (only when LIBRARY_SYNC_HOURS is set)
|
| 27 |
+
yield
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
+
app = FastAPI(title="NoteScanner API", lifespan=lifespan)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
|
| 33 |
+
@app.middleware("http")
|
| 34 |
+
async def json_errors(request: Request, call_next):
|
| 35 |
+
"""Turn unexpected crashes into a JSON error. Added before CORS so the browser can read it."""
|
| 36 |
try:
|
| 37 |
+
return await call_next(request)
|
| 38 |
+
except Exception as e:
|
| 39 |
+
logger.exception("Unhandled error on %s %s", request.method, request.url.path)
|
| 40 |
+
alerts.notify("server-error", f"{request.method} {request.url.path}: {type(e).__name__}: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
return JSONResponse(
|
| 42 |
+
{"error": "Something went wrong on the server. Please try again."},
|
| 43 |
+
status_code=500,
|
| 44 |
)
|
| 45 |
|
| 46 |
|
| 47 |
+
@app.middleware("http")
|
| 48 |
+
async def request_limits(request: Request, call_next):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
"""
|
| 50 |
+
Overall cap on every request per network address and per signed-in browser, checked before
|
| 51 |
+
any route runs (routes add their own tighter limits). Added before CORS so the 429 is readable.
|
| 52 |
"""
|
| 53 |
+
if request.url.path not in settings.UNLIMITED_PATHS:
|
| 54 |
+
rules = [("all-ip", rate_limit.client_ip(request), *settings.LIMIT_ALL_PER_IP, None)]
|
| 55 |
+
session_id = (request.headers.get(SESSION_HEADER) or "").strip()
|
| 56 |
+
if session_id:
|
| 57 |
+
rules.append(("all-session", session_id, *settings.LIMIT_ALL_PER_SESSION, None))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
try:
|
| 59 |
+
rate_limit.check_all(rules)
|
| 60 |
+
except HTTPException as e:
|
| 61 |
+
return JSONResponse({"detail": e.detail}, status_code=e.status_code, headers=e.headers)
|
| 62 |
+
return await call_next(request)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
|
| 65 |
+
app.add_middleware(
|
| 66 |
+
CORSMiddleware,
|
| 67 |
+
allow_origins=allowed_origins(),
|
| 68 |
+
allow_credentials=False, # auth uses the X-Session-Id header, not cookies
|
| 69 |
+
allow_methods=["*"],
|
| 70 |
+
allow_headers=["*"],
|
| 71 |
+
expose_headers=["Content-Disposition", "Retry-After"],
|
| 72 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
+
for module in (account, files, chat, study, onenote, admin, library_routes):
|
| 75 |
+
app.include_router(module.router)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
|
| 78 |
+
@app.get("/health")
|
| 79 |
+
def health():
|
| 80 |
+
"""Liveness check for Docker / the hosting platform (doesn't touch the database)."""
|
| 81 |
+
return {"status": "ok"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
|
| 84 |
+
@app.get("/config")
|
| 85 |
+
def public_config():
|
| 86 |
+
"""Feature flags the frontend needs before sign-in."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
return {
|
| 88 |
+
"password_reset_enabled": mailer.is_configured(),
|
| 89 |
+
"onenote_configured": onenote_sync.is_configured(),
|
| 90 |
+
"max_upload_mb": MAX_UPLOAD_MB,
|
| 91 |
+
"max_chat_files": MAX_CHAT_FILES_PER_SESSION,
|
| 92 |
+
"reminders_available": preferences.reminders_available(),
|
| 93 |
+
"languages": list(settings.ANSWER_LANGUAGES),
|
| 94 |
}
|
| 95 |
|
| 96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
if __name__ == "__main__":
|
| 98 |
import uvicorn
|
| 99 |
+
|
| 100 |
uvicorn.run(app, host="0.0.0.0", port=8000)
|
backend/auth.py
CHANGED
|
@@ -1,11 +1,16 @@
|
|
| 1 |
"""Simple session-based auth (no JWT) and password hashing for NoteScanner."""
|
| 2 |
-
|
|
|
|
| 3 |
|
| 4 |
-
from
|
|
|
|
|
|
|
| 5 |
|
| 6 |
# Re-export for callers that import from auth
|
| 7 |
from passlib.context import CryptContext
|
| 8 |
|
|
|
|
|
|
|
| 9 |
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 10 |
|
| 11 |
SESSION_HEADER = "X-Session-Id"
|
|
@@ -24,22 +29,63 @@ def create_session(user_id: str) -> str:
|
|
| 24 |
return session_create(user_id)
|
| 25 |
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
def get_user_id_from_session(session_id: str) -> str | None:
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
def get_effective_user(request: Request) -> tuple[str, bool]:
|
| 32 |
"""
|
| 33 |
Returns (effective_user_id, is_guest).
|
| 34 |
-
- If X-Session-Id is
|
| 35 |
-
- Else if X-Guest-Id
|
| 36 |
- Else raises ValueError (caller should return 400; client must call GET /guest_id first).
|
| 37 |
"""
|
| 38 |
-
|
| 39 |
-
user_id = get_user_id_from_session(session_id)
|
| 40 |
if user_id:
|
| 41 |
return user_id, False
|
| 42 |
-
guest_id = request.headers.get(GUEST_HEADER)
|
| 43 |
-
if guest_id:
|
| 44 |
return f"guest_{guest_id}", True
|
| 45 |
raise ValueError("Missing X-Guest-Id. Call GET /guest_id first or sign in.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""Simple session-based auth (no JWT) and password hashing for NoteScanner."""
|
| 2 |
+
import logging
|
| 3 |
+
import uuid
|
| 4 |
|
| 5 |
+
from fastapi import HTTPException, Request
|
| 6 |
+
|
| 7 |
+
from backend.chroma_store import session_create, session_delete, session_get_user_id
|
| 8 |
|
| 9 |
# Re-export for callers that import from auth
|
| 10 |
from passlib.context import CryptContext
|
| 11 |
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 15 |
|
| 16 |
SESSION_HEADER = "X-Session-Id"
|
|
|
|
| 29 |
return session_create(user_id)
|
| 30 |
|
| 31 |
|
| 32 |
+
def end_session(session_id: str | None) -> None:
|
| 33 |
+
session_delete(session_id or "")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
def get_user_id_from_session(session_id: str) -> str | None:
|
| 37 |
+
"""User id for a live session. Raises HTTP 503 if the database can't be reached."""
|
| 38 |
+
try:
|
| 39 |
+
return session_get_user_id(session_id)
|
| 40 |
+
except Exception:
|
| 41 |
+
logger.exception("Session lookup failed")
|
| 42 |
+
raise HTTPException(
|
| 43 |
+
status_code=503,
|
| 44 |
+
detail="Can't reach the database right now. Please try again in a moment.",
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _valid_guest_id(guest_id: str) -> bool:
|
| 49 |
+
try:
|
| 50 |
+
uuid.UUID(guest_id)
|
| 51 |
+
return True
|
| 52 |
+
except (ValueError, AttributeError, TypeError):
|
| 53 |
+
return False
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _signed_in_user_or_none(request: Request) -> str | None:
|
| 57 |
+
"""
|
| 58 |
+
User id for the X-Session-Id header, None if no header was sent.
|
| 59 |
+
A header that no longer matches a live session raises HTTP 401 so the app can sign out.
|
| 60 |
+
"""
|
| 61 |
+
session_id = (request.headers.get(SESSION_HEADER) or "").strip()
|
| 62 |
+
if not session_id:
|
| 63 |
+
return None
|
| 64 |
+
user_id = get_user_id_from_session(session_id)
|
| 65 |
+
if not user_id:
|
| 66 |
+
raise HTTPException(status_code=401, detail="Your session has expired. Please sign in again.")
|
| 67 |
+
return user_id
|
| 68 |
|
| 69 |
|
| 70 |
def get_effective_user(request: Request) -> tuple[str, bool]:
|
| 71 |
"""
|
| 72 |
Returns (effective_user_id, is_guest).
|
| 73 |
+
- If X-Session-Id is sent -> (user_id, False), or HTTP 401 if that session is no longer valid.
|
| 74 |
+
- Else if X-Guest-Id is a valid id -> ("guest_<id>", True).
|
| 75 |
- Else raises ValueError (caller should return 400; client must call GET /guest_id first).
|
| 76 |
"""
|
| 77 |
+
user_id = _signed_in_user_or_none(request)
|
|
|
|
| 78 |
if user_id:
|
| 79 |
return user_id, False
|
| 80 |
+
guest_id = (request.headers.get(GUEST_HEADER) or "").strip()
|
| 81 |
+
if guest_id and _valid_guest_id(guest_id):
|
| 82 |
return f"guest_{guest_id}", True
|
| 83 |
raise ValueError("Missing X-Guest-Id. Call GET /guest_id first or sign in.")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def require_signed_in_user(request: Request) -> str:
|
| 87 |
+
"""User id for routes that store data or call paid AI services; HTTP 401 for guests."""
|
| 88 |
+
user_id = _signed_in_user_or_none(request)
|
| 89 |
+
if not user_id:
|
| 90 |
+
raise HTTPException(status_code=401, detail="Please sign in to continue.")
|
| 91 |
+
return user_id
|
backend/chat_cache.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Temporary per-chat uploads (the + button in chat), kept only in this process's memory."""
|
| 2 |
+
import threading
|
| 3 |
+
import time
|
| 4 |
+
|
| 5 |
+
from fastapi import HTTPException
|
| 6 |
+
|
| 7 |
+
from backend.settings import CHAT_CACHE_TTL_SECONDS, MAX_CHAT_FILES_PER_SESSION
|
| 8 |
+
|
| 9 |
+
_cache: dict[str, dict] = {}
|
| 10 |
+
_lock = threading.Lock()
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _key(user_id: str, chat_session_id: str) -> str:
|
| 14 |
+
return f"{user_id}::{(chat_session_id or '').strip()}"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _prune_locked(now: float) -> None:
|
| 18 |
+
"""Drop chat sessions nobody has used for CHAT_CACHE_TTL_SECONDS (e.g. the tab was closed)."""
|
| 19 |
+
expired = [k for k, v in _cache.items() if now - v["last_used"] > CHAT_CACHE_TTL_SECONDS]
|
| 20 |
+
for k in expired:
|
| 21 |
+
del _cache[k]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def count(user_id: str, chat_session_id: str) -> int:
|
| 25 |
+
with _lock:
|
| 26 |
+
entry = _cache.get(_key(user_id, chat_session_id))
|
| 27 |
+
return len(entry["items"]) if entry else 0
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def add(user_id: str, chat_session_id: str, item: dict) -> int:
|
| 31 |
+
now = time.time()
|
| 32 |
+
with _lock:
|
| 33 |
+
_prune_locked(now)
|
| 34 |
+
entry = _cache.setdefault(_key(user_id, chat_session_id), {"items": [], "last_used": now})
|
| 35 |
+
if len(entry["items"]) >= MAX_CHAT_FILES_PER_SESSION:
|
| 36 |
+
raise HTTPException(
|
| 37 |
+
status_code=400,
|
| 38 |
+
detail=f"This chat already has {MAX_CHAT_FILES_PER_SESSION} files. Start a new chat to add more.",
|
| 39 |
+
)
|
| 40 |
+
entry["items"].append(item)
|
| 41 |
+
entry["last_used"] = now
|
| 42 |
+
return len(entry["items"])
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def items(user_id: str, chat_session_id: str) -> list[dict]:
|
| 46 |
+
if not (chat_session_id or "").strip():
|
| 47 |
+
return []
|
| 48 |
+
now = time.time()
|
| 49 |
+
with _lock:
|
| 50 |
+
_prune_locked(now)
|
| 51 |
+
entry = _cache.get(_key(user_id, chat_session_id))
|
| 52 |
+
if not entry:
|
| 53 |
+
return []
|
| 54 |
+
entry["last_used"] = now
|
| 55 |
+
return list(entry["items"])
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def clear(user_id: str, chat_session_id: str) -> int:
|
| 59 |
+
with _lock:
|
| 60 |
+
entry = _cache.pop(_key(user_id, chat_session_id), None)
|
| 61 |
+
return len(entry["items"]) if entry else 0
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def clear_user(user_id: str) -> None:
|
| 65 |
+
prefix = f"{user_id}::"
|
| 66 |
+
with _lock:
|
| 67 |
+
for k in [k for k in _cache if k.startswith(prefix)]:
|
| 68 |
+
del _cache[k]
|
backend/chroma_store.py
CHANGED
|
@@ -2,31 +2,70 @@
|
|
| 2 |
Single-database store using ChromaDB for NoteScanner.
|
| 3 |
|
| 4 |
Stores:
|
| 5 |
-
- Users, sessions: metadata + dummy embeddings
|
| 6 |
-
- user_documents: full extracted text per logical path
|
| 7 |
- user_{user_id}_notes: chunk text + embeddings + metadata (RAG / search)
|
| 8 |
- user_{user_id}_vfs: explorer tree + file_meta JSON (structural metadata; not PDF/image binaries)
|
|
|
|
| 9 |
|
| 10 |
Connection:
|
| 11 |
- If CHROMA_API_KEY is set → Chroma Cloud (CHROMA_TENANT, CHROMA_DATABASE; optional CHROMA_HOST override via settings if supported)
|
| 12 |
- Else → self-hosted HttpClient (CHROMA_HOST, CHROMA_PORT, optional CHROMA_SSL=true)
|
|
|
|
|
|
|
|
|
|
| 13 |
"""
|
|
|
|
| 14 |
import json
|
|
|
|
| 15 |
import os
|
|
|
|
| 16 |
import uuid
|
| 17 |
import time
|
| 18 |
import chromadb
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
EMBEDDING_DIM = 384 # all-MiniLM-L6-v2
|
| 21 |
-
USER_DOCUMENT_MAX_BYTES = int((os.getenv("USER_DOCUMENT_MAX_BYTES") or "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
_global_client = None
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
def _dummy_embedding():
|
| 27 |
return [0.0] * EMBEDDING_DIM
|
| 28 |
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
def get_global_client():
|
| 31 |
global _global_client
|
| 32 |
if _global_client is None:
|
|
@@ -56,33 +95,132 @@ def _get_or_create_collection(name: str):
|
|
| 56 |
client = get_global_client()
|
| 57 |
try:
|
| 58 |
return client.get_collection(name=name)
|
| 59 |
-
except
|
| 60 |
return client.create_collection(name=name, metadata={"description": "NoteScanner"})
|
| 61 |
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
def get_user_collection(user_id: str):
|
| 64 |
"""Get or create the per-user RAG collection for note chunks (user_{user_id}_notes)."""
|
| 65 |
name = f"user_{user_id}_notes"
|
| 66 |
return _get_or_create_collection(name)
|
| 67 |
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
def user_notes_concat_text_for_path(user_id: str, path: str) -> str:
|
| 70 |
"""
|
| 71 |
-
|
| 72 |
-
PDFs/images are ingested under the original path (e.g. Maths/L3.1_Part1.pdf), not only user_documents.
|
| 73 |
"""
|
| 74 |
p = (path or "").replace("\\", "/").strip()
|
| 75 |
if not p:
|
| 76 |
return ""
|
| 77 |
-
col =
|
| 78 |
-
|
| 79 |
-
res = col.get(where={"path": p}, include=["documents", "metadatas"])
|
| 80 |
-
except Exception:
|
| 81 |
return ""
|
|
|
|
| 82 |
docs = res.get("documents") or []
|
| 83 |
metas = res.get("metadatas") or []
|
| 84 |
-
if not docs:
|
| 85 |
-
return ""
|
| 86 |
pairs: list[tuple[int, str]] = []
|
| 87 |
for i, doc in enumerate(docs):
|
| 88 |
meta = metas[i] if i < len(metas) else {}
|
|
@@ -96,20 +234,29 @@ def user_notes_concat_text_for_path(user_id: str, path: str) -> str:
|
|
| 96 |
if text:
|
| 97 |
pairs.append((idx, text))
|
| 98 |
pairs.sort(key=lambda x: x[0])
|
| 99 |
-
return
|
| 100 |
|
| 101 |
|
| 102 |
def delete_user_notes_collection(user_id: str) -> bool:
|
| 103 |
"""Delete the entire per-user RAG collection. Returns True if deleted, False if it did not exist."""
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
|
|
|
|
| 113 |
def get_user_vfs_collection(user_id: str):
|
| 114 |
"""Virtual folder tree + file metadata (JSON documents). Binaries are not stored."""
|
| 115 |
name = f"user_{user_id}_vfs"
|
|
@@ -118,89 +265,116 @@ def get_user_vfs_collection(user_id: str):
|
|
| 118 |
|
| 119 |
VFS_TREE_DOC_ID = "vfs_tree"
|
| 120 |
VFS_FILE_META_DOC_ID = "vfs_file_meta"
|
|
|
|
| 121 |
|
| 122 |
|
| 123 |
-
def
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
| 127 |
if not res.get("ids"):
|
| 128 |
-
return
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
|
| 136 |
def vfs_set_tree(user_id: str, tree: list) -> None:
|
| 137 |
-
|
| 138 |
-
doc = json.dumps(tree, ensure_ascii=False)
|
| 139 |
-
try:
|
| 140 |
-
col.delete(ids=[VFS_TREE_DOC_ID])
|
| 141 |
-
except Exception:
|
| 142 |
-
pass
|
| 143 |
-
col.add(
|
| 144 |
-
ids=[VFS_TREE_DOC_ID],
|
| 145 |
-
documents=[doc],
|
| 146 |
-
embeddings=[_dummy_embedding()],
|
| 147 |
-
metadatas=[{"kind": "vfs_tree"}],
|
| 148 |
-
)
|
| 149 |
|
| 150 |
|
| 151 |
def vfs_get_file_meta_dict(user_id: str) -> dict:
|
| 152 |
-
|
| 153 |
-
try:
|
| 154 |
-
res = col.get(ids=[VFS_FILE_META_DOC_ID], include=["documents"])
|
| 155 |
-
if not res.get("ids"):
|
| 156 |
-
return {}
|
| 157 |
-
raw = (res.get("documents") or [""])[0] or "{}"
|
| 158 |
-
data = json.loads(raw)
|
| 159 |
-
return data if isinstance(data, dict) else {}
|
| 160 |
-
except Exception:
|
| 161 |
-
return {}
|
| 162 |
|
| 163 |
|
| 164 |
def vfs_set_file_meta_dict(user_id: str, meta: dict) -> None:
|
| 165 |
-
|
| 166 |
-
doc = json.dumps(meta, ensure_ascii=False)
|
| 167 |
-
try:
|
| 168 |
-
col.delete(ids=[VFS_FILE_META_DOC_ID])
|
| 169 |
-
except Exception:
|
| 170 |
-
pass
|
| 171 |
-
col.add(
|
| 172 |
-
ids=[VFS_FILE_META_DOC_ID],
|
| 173 |
-
documents=[doc],
|
| 174 |
-
embeddings=[_dummy_embedding()],
|
| 175 |
-
metadatas=[{"kind": "vfs_file_meta"}],
|
| 176 |
-
)
|
| 177 |
|
| 178 |
|
| 179 |
-
def
|
| 180 |
-
|
| 181 |
-
name = f"user_{user_id}_vfs"
|
| 182 |
try:
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
return False
|
| 187 |
|
| 188 |
|
| 189 |
-
def
|
| 190 |
-
""
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
for p in paths:
|
| 196 |
-
try:
|
| 197 |
-
res = col.get(where={"path": p}, include=[])
|
| 198 |
-
ids_to_drop.extend(res.get("ids") or [])
|
| 199 |
-
except Exception:
|
| 200 |
-
continue
|
| 201 |
-
if ids_to_drop:
|
| 202 |
-
col.delete(ids=ids_to_drop)
|
| 203 |
-
return len(ids_to_drop)
|
| 204 |
|
| 205 |
|
| 206 |
# ---------- Users ----------
|
|
@@ -210,48 +384,78 @@ def get_users_collection():
|
|
| 210 |
|
| 211 |
def user_exists_by_email(email: str) -> bool:
|
| 212 |
col = get_users_collection()
|
| 213 |
-
res = col.get(where={"email": email.lower()})
|
| 214 |
return len(res["ids"]) > 0
|
| 215 |
|
| 216 |
|
| 217 |
-
def user_create(email: str, hashed_password: str, name: str) -> str:
|
| 218 |
user_id = str(uuid.uuid4())
|
| 219 |
col = get_users_collection()
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
|
|
|
|
|
|
| 226 |
return user_id
|
| 227 |
|
| 228 |
|
| 229 |
-
def
|
| 230 |
-
col = get_users_collection()
|
| 231 |
-
res = col.get(where={"email": email.lower()})
|
| 232 |
if not res["ids"]:
|
| 233 |
return None
|
| 234 |
-
|
|
|
|
| 235 |
"user_id": res["ids"][0],
|
| 236 |
-
"email":
|
| 237 |
-
"
|
| 238 |
-
|
|
|
|
| 239 |
}
|
|
|
|
|
|
|
|
|
|
| 240 |
|
| 241 |
|
| 242 |
-
def
|
| 243 |
col = get_users_collection()
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
|
| 256 |
|
| 257 |
# ---------- Sessions ----------
|
|
@@ -259,40 +463,111 @@ def get_sessions_collection():
|
|
| 259 |
return _get_or_create_collection("sessions")
|
| 260 |
|
| 261 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
def session_create(user_id: str) -> str:
|
| 263 |
session_id = str(uuid.uuid4())
|
|
|
|
| 264 |
col = get_sessions_collection()
|
|
|
|
| 265 |
col.add(
|
| 266 |
ids=[session_id],
|
| 267 |
documents=[""],
|
| 268 |
-
metadatas=[{"user_id": user_id}],
|
| 269 |
embeddings=[_dummy_embedding()],
|
| 270 |
)
|
| 271 |
return session_id
|
| 272 |
|
| 273 |
|
| 274 |
def session_get_user_id(session_id: str) -> str | None:
|
|
|
|
| 275 |
if not session_id:
|
| 276 |
return None
|
| 277 |
col = get_sessions_collection()
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
|
|
|
| 284 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
|
| 286 |
|
| 287 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
def get_user_documents_collection():
|
| 289 |
return _get_or_create_collection("user_documents")
|
| 290 |
|
| 291 |
|
| 292 |
-
def
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
|
| 298 |
def _truncate_utf8_bytes(text: str, max_bytes: int) -> tuple[str, int]:
|
|
@@ -309,79 +584,88 @@ def _truncate_utf8_bytes(text: str, max_bytes: int) -> tuple[str, int]:
|
|
| 309 |
|
| 310 |
|
| 311 |
def user_document_upsert(user_id: str, path: str, content: str, original_filename: str):
|
| 312 |
-
"""Store extracted text for a path
|
| 313 |
col = get_user_documents_collection()
|
| 314 |
-
doc_id = _doc_id(user_id, path)
|
| 315 |
trimmed, full_bytes = _truncate_utf8_bytes(content or "", USER_DOCUMENT_MAX_BYTES)
|
| 316 |
stored_bytes = len((trimmed or "").encode("utf-8"))
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
)
|
|
|
|
| 333 |
|
| 334 |
|
| 335 |
-
def
|
| 336 |
-
"""
|
| 337 |
-
|
| 338 |
-
res = col.get(where={"user_id": user_id})
|
| 339 |
if not res["ids"]:
|
| 340 |
-
return
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
|
| 349 |
|
| 350 |
def user_document_delete_by_path(user_id: str, path: str):
|
| 351 |
-
doc_id = _doc_id(user_id, path)
|
| 352 |
col = get_user_documents_collection()
|
| 353 |
-
|
| 354 |
-
col.delete(ids=[doc_id])
|
| 355 |
-
except Exception:
|
| 356 |
-
pass
|
| 357 |
|
| 358 |
|
| 359 |
-
def
|
|
|
|
| 360 |
col = get_user_documents_collection()
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
except Exception:
|
| 369 |
-
return None
|
| 370 |
|
| 371 |
|
| 372 |
def user_documents_relocate_prefix(user_id: str, old_prefix: str, new_prefix: str) -> int:
|
| 373 |
"""Rename stored document paths under old_prefix to new_prefix (longest paths first)."""
|
| 374 |
col = get_user_documents_collection()
|
| 375 |
-
res =
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
for m in metas:
|
| 379 |
p = ((m or {}).get("path") or "").replace("\\", "/")
|
| 380 |
-
if p == old_prefix:
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
pairs.append((p, new_prefix + p[len(old_prefix) :]))
|
| 384 |
-
pairs.sort(key=lambda x: -len(x[0]))
|
| 385 |
n = 0
|
| 386 |
for op, np in pairs:
|
| 387 |
if op != np and user_document_rename_path(user_id, op, np):
|
|
@@ -391,20 +675,13 @@ def user_documents_relocate_prefix(user_id: str, old_prefix: str, new_prefix: st
|
|
| 391 |
|
| 392 |
def user_document_rename_path(user_id: str, old_path: str, new_path: str) -> bool:
|
| 393 |
"""Move stored extracted text from old_path to new_path."""
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
try:
|
| 397 |
-
res = col.get(ids=[oid], include=["documents", "metadatas"])
|
| 398 |
-
if not res.get("ids"):
|
| 399 |
-
return False
|
| 400 |
-
content = (res.get("documents") or [""])[0] or ""
|
| 401 |
-
meta = res.get("metadatas")[0] or {}
|
| 402 |
-
ofn = meta.get("original_filename") or os.path.basename(new_path.replace("\\", "/"))
|
| 403 |
-
col.delete(ids=[oid])
|
| 404 |
-
user_document_upsert(user_id, new_path, content, ofn)
|
| 405 |
-
return True
|
| 406 |
-
except Exception:
|
| 407 |
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
| 408 |
|
| 409 |
|
| 410 |
# ---------- OneNote OAuth tokens/state ----------
|
|
@@ -450,6 +727,7 @@ def onenote_oauth_state_pop_user_id(state: str) -> str | None:
|
|
| 450 |
return None
|
| 451 |
return user_id
|
| 452 |
except Exception:
|
|
|
|
| 453 |
return None
|
| 454 |
|
| 455 |
|
|
@@ -484,4 +762,9 @@ def onenote_token_get(user_id: str) -> dict | None:
|
|
| 484 |
data = json.loads(raw)
|
| 485 |
return data if isinstance(data, dict) else None
|
| 486 |
except Exception:
|
|
|
|
| 487 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
Single-database store using ChromaDB for NoteScanner.
|
| 3 |
|
| 4 |
Stores:
|
| 5 |
+
- Users, sessions, password-reset tokens: metadata + dummy embeddings
|
| 6 |
+
- user_documents: full extracted text per logical path (split into parts) + dummy embedding
|
| 7 |
- user_{user_id}_notes: chunk text + embeddings + metadata (RAG / search)
|
| 8 |
- user_{user_id}_vfs: explorer tree + file_meta JSON (structural metadata; not PDF/image binaries)
|
| 9 |
+
- user_{user_id}_study: flashcard decks and cards (see study_store.py)
|
| 10 |
|
| 11 |
Connection:
|
| 12 |
- If CHROMA_API_KEY is set → Chroma Cloud (CHROMA_TENANT, CHROMA_DATABASE; optional CHROMA_HOST override via settings if supported)
|
| 13 |
- Else → self-hosted HttpClient (CHROMA_HOST, CHROMA_PORT, optional CHROMA_SSL=true)
|
| 14 |
+
|
| 15 |
+
Chroma Cloud limits this module works within: a get/query returns at most 300 records, a write
|
| 16 |
+
takes at most 300 records, a document is at most 16 KB, and a record id is at most 128 bytes.
|
| 17 |
"""
|
| 18 |
+
import hashlib
|
| 19 |
import json
|
| 20 |
+
import logging
|
| 21 |
import os
|
| 22 |
+
import threading
|
| 23 |
import uuid
|
| 24 |
import time
|
| 25 |
import chromadb
|
| 26 |
+
from chromadb.errors import NotFoundError
|
| 27 |
+
|
| 28 |
+
logger = logging.getLogger(__name__)
|
| 29 |
|
| 30 |
EMBEDDING_DIM = 384 # all-MiniLM-L6-v2
|
| 31 |
+
USER_DOCUMENT_MAX_BYTES = int((os.getenv("USER_DOCUMENT_MAX_BYTES") or "2000000").strip() or "2000000")
|
| 32 |
+
SESSION_TTL_SECONDS = int(float((os.getenv("SESSION_TTL_DAYS") or "14").strip() or "14") * 86400)
|
| 33 |
+
PASSWORD_RESET_TTL_SECONDS = 3600
|
| 34 |
+
|
| 35 |
+
PAGE_SIZE = 250 # records per get() page (Chroma Cloud max is 300)
|
| 36 |
+
WRITE_BATCH = 250 # records per add/upsert/update/delete call (Chroma Cloud max is 300)
|
| 37 |
+
TEXT_PART_CHARS = 3500 # ≤ 14 KB even at 4 bytes per character (Chroma Cloud max document is 16 KB)
|
| 38 |
|
| 39 |
_global_client = None
|
| 40 |
|
| 41 |
+
_user_locks: dict[str, threading.RLock] = {}
|
| 42 |
+
_user_locks_guard = threading.Lock()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def user_lock(user_id: str) -> threading.RLock:
|
| 46 |
+
"""Per-user lock so two requests can't overwrite each other's folder tree or file metadata."""
|
| 47 |
+
with _user_locks_guard:
|
| 48 |
+
lock = _user_locks.get(user_id)
|
| 49 |
+
if lock is None:
|
| 50 |
+
lock = _user_locks[user_id] = threading.RLock()
|
| 51 |
+
return lock
|
| 52 |
+
|
| 53 |
|
| 54 |
def _dummy_embedding():
|
| 55 |
return [0.0] * EMBEDDING_DIM
|
| 56 |
|
| 57 |
|
| 58 |
+
def short_id(prefix: str, *parts: str) -> str:
|
| 59 |
+
"""Fixed-length record id (Chroma Cloud ids are limited to 128 bytes; paths can be longer)."""
|
| 60 |
+
digest = hashlib.sha256("\x1f".join(str(p) for p in parts).encode("utf-8")).hexdigest()[:40]
|
| 61 |
+
return f"{prefix}{digest}"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def split_text_parts(text: str, size: int = TEXT_PART_CHARS) -> list[str]:
|
| 65 |
+
text = text or ""
|
| 66 |
+
return [text[i : i + size] for i in range(0, len(text), size)] or [""]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
def get_global_client():
|
| 70 |
global _global_client
|
| 71 |
if _global_client is None:
|
|
|
|
| 95 |
client = get_global_client()
|
| 96 |
try:
|
| 97 |
return client.get_collection(name=name)
|
| 98 |
+
except NotFoundError:
|
| 99 |
return client.create_collection(name=name, metadata={"description": "NoteScanner"})
|
| 100 |
|
| 101 |
|
| 102 |
+
def _get_collection_or_none(name: str):
|
| 103 |
+
"""Existing collection, or None if it was never created. Other errors (e.g. no connection) raise."""
|
| 104 |
+
try:
|
| 105 |
+
return get_global_client().get_collection(name=name)
|
| 106 |
+
except NotFoundError:
|
| 107 |
+
return None
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _delete_collection(name: str) -> bool:
|
| 111 |
+
try:
|
| 112 |
+
get_global_client().delete_collection(name=name)
|
| 113 |
+
return True
|
| 114 |
+
except NotFoundError:
|
| 115 |
+
return False
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# ---------- Paging and batching helpers (Chroma Cloud limits) ----------
|
| 119 |
+
def get_all(col, **kwargs) -> dict:
|
| 120 |
+
"""
|
| 121 |
+
col.get() across pages. Returns {"ids": [...], "documents": [...]|None, "metadatas": [...]|None,
|
| 122 |
+
"embeddings": [...]|None}, with lists aligned to ids.
|
| 123 |
+
"""
|
| 124 |
+
out: dict = {"ids": [], "documents": None, "metadatas": None, "embeddings": None}
|
| 125 |
+
offset = 0
|
| 126 |
+
while True:
|
| 127 |
+
res = col.get(limit=PAGE_SIZE, offset=offset, **kwargs)
|
| 128 |
+
page_ids = list(res.get("ids") or [])
|
| 129 |
+
out["ids"].extend(page_ids)
|
| 130 |
+
for key in ("documents", "metadatas", "embeddings"):
|
| 131 |
+
vals = res.get(key)
|
| 132 |
+
if vals is not None:
|
| 133 |
+
if out[key] is None:
|
| 134 |
+
out[key] = []
|
| 135 |
+
out[key].extend(list(vals))
|
| 136 |
+
if len(page_ids) < PAGE_SIZE:
|
| 137 |
+
return out
|
| 138 |
+
offset += PAGE_SIZE
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def delete_ids(col, ids: list[str]) -> int:
|
| 142 |
+
ids = list(ids or [])
|
| 143 |
+
for i in range(0, len(ids), WRITE_BATCH):
|
| 144 |
+
col.delete(ids=ids[i : i + WRITE_BATCH])
|
| 145 |
+
return len(ids)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def write_records(col, method: str, ids: list[str], **fields) -> None:
|
| 149 |
+
"""add/upsert/update in batches; `fields` are lists aligned with ids (documents, embeddings, metadatas)."""
|
| 150 |
+
fn = getattr(col, method)
|
| 151 |
+
for i in range(0, len(ids), WRITE_BATCH):
|
| 152 |
+
batch = {k: v[i : i + WRITE_BATCH] for k, v in fields.items() if v is not None}
|
| 153 |
+
fn(ids=ids[i : i + WRITE_BATCH], **batch)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def collection_distance_space(col) -> str:
|
| 157 |
+
"""Distance type the collection was created with: 'l2' (Chroma default), 'cosine' or 'ip'."""
|
| 158 |
+
space = None
|
| 159 |
+
try:
|
| 160 |
+
cfg = getattr(col, "configuration_json", None) or {}
|
| 161 |
+
for index in ("hnsw", "spann"):
|
| 162 |
+
space = space or ((cfg.get(index) or {}).get("space"))
|
| 163 |
+
except Exception:
|
| 164 |
+
space = None
|
| 165 |
+
if not space:
|
| 166 |
+
space = (getattr(col, "metadata", None) or {}).get("hnsw:space")
|
| 167 |
+
return str(space or "l2").lower()
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def distance_to_similarity(distance: float, space: str) -> float:
|
| 171 |
+
"""
|
| 172 |
+
Convert a Chroma distance into cosine similarity (-1..1), the same scale used for chat uploads.
|
| 173 |
+
Embeddings are unit length, so squared L2 distance = 2 - 2*cos.
|
| 174 |
+
"""
|
| 175 |
+
if space == "l2":
|
| 176 |
+
return 1.0 - distance / 2.0
|
| 177 |
+
return 1.0 - distance # cosine and ip distances are 1 - cos for unit vectors
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# ---------- Per-user note chunks ----------
|
| 181 |
def get_user_collection(user_id: str):
|
| 182 |
"""Get or create the per-user RAG collection for note chunks (user_{user_id}_notes)."""
|
| 183 |
name = f"user_{user_id}_notes"
|
| 184 |
return _get_or_create_collection(name)
|
| 185 |
|
| 186 |
|
| 187 |
+
def chunk_ids_for_path(path: str, count: int, start: int = 0) -> list[str]:
|
| 188 |
+
base = short_id("c", path)
|
| 189 |
+
return [f"{base}_{start + j}" for j in range(count)]
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def join_chunks(chunks: list[str], max_overlap: int = 300) -> str:
|
| 193 |
+
"""Join ordered chunks, dropping the text repeated between neighbours (chunks overlap on purpose)."""
|
| 194 |
+
out = ""
|
| 195 |
+
for ch in chunks:
|
| 196 |
+
if not out:
|
| 197 |
+
out = ch
|
| 198 |
+
continue
|
| 199 |
+
overlap = 0
|
| 200 |
+
for k in range(min(max_overlap, len(ch), len(out)), 0, -1):
|
| 201 |
+
if out.endswith(ch[:k]):
|
| 202 |
+
overlap = k
|
| 203 |
+
break
|
| 204 |
+
if overlap:
|
| 205 |
+
out += ch[overlap:]
|
| 206 |
+
else:
|
| 207 |
+
out += "\n\n" + ch
|
| 208 |
+
return out
|
| 209 |
+
|
| 210 |
+
|
| 211 |
def user_notes_concat_text_for_path(user_id: str, path: str) -> str:
|
| 212 |
"""
|
| 213 |
+
Full text of a file rebuilt from its search chunks, in order, without the repeated overlap.
|
|
|
|
| 214 |
"""
|
| 215 |
p = (path or "").replace("\\", "/").strip()
|
| 216 |
if not p:
|
| 217 |
return ""
|
| 218 |
+
col = _get_collection_or_none(f"user_{user_id}_notes")
|
| 219 |
+
if col is None:
|
|
|
|
|
|
|
| 220 |
return ""
|
| 221 |
+
res = get_all(col, where={"path": p}, include=["documents", "metadatas"])
|
| 222 |
docs = res.get("documents") or []
|
| 223 |
metas = res.get("metadatas") or []
|
|
|
|
|
|
|
| 224 |
pairs: list[tuple[int, str]] = []
|
| 225 |
for i, doc in enumerate(docs):
|
| 226 |
meta = metas[i] if i < len(metas) else {}
|
|
|
|
| 234 |
if text:
|
| 235 |
pairs.append((idx, text))
|
| 236 |
pairs.sort(key=lambda x: x[0])
|
| 237 |
+
return join_chunks([t for _, t in pairs])
|
| 238 |
|
| 239 |
|
| 240 |
def delete_user_notes_collection(user_id: str) -> bool:
|
| 241 |
"""Delete the entire per-user RAG collection. Returns True if deleted, False if it did not exist."""
|
| 242 |
+
return _delete_collection(f"user_{user_id}_notes")
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def delete_user_notes_by_paths(user_id: str, paths: list[str]) -> int:
|
| 246 |
+
"""Delete chunks whose metadata path is in paths. Returns number of ids deleted."""
|
| 247 |
+
if not paths:
|
| 248 |
+
return 0
|
| 249 |
+
col = _get_collection_or_none(f"user_{user_id}_notes")
|
| 250 |
+
if col is None:
|
| 251 |
+
return 0
|
| 252 |
+
deleted = 0
|
| 253 |
+
for p in paths:
|
| 254 |
+
ids = get_all(col, where={"path": p}, include=[])["ids"]
|
| 255 |
+
deleted += delete_ids(col, ids)
|
| 256 |
+
return deleted
|
| 257 |
|
| 258 |
|
| 259 |
+
# ---------- Per-user folder tree + file metadata ----------
|
| 260 |
def get_user_vfs_collection(user_id: str):
|
| 261 |
"""Virtual folder tree + file metadata (JSON documents). Binaries are not stored."""
|
| 262 |
name = f"user_{user_id}_vfs"
|
|
|
|
| 265 |
|
| 266 |
VFS_TREE_DOC_ID = "vfs_tree"
|
| 267 |
VFS_FILE_META_DOC_ID = "vfs_file_meta"
|
| 268 |
+
VFS_STORAGE_VERSION_DOC_ID = "vfs_storage_version"
|
| 269 |
|
| 270 |
|
| 271 |
+
def _read_parts(col, doc_id: str) -> str | None:
|
| 272 |
+
"""
|
| 273 |
+
Read a JSON document stored as a manifest record (`doc_id`) plus parts (`doc_id#<version>#<k>`).
|
| 274 |
+
Older single-record documents (no `parts` in the manifest) are read directly. None if missing.
|
| 275 |
+
"""
|
| 276 |
+
for _attempt in range(2):
|
| 277 |
+
res = col.get(ids=[doc_id], include=["documents", "metadatas"])
|
| 278 |
if not res.get("ids"):
|
| 279 |
+
return None
|
| 280 |
+
meta = (res.get("metadatas") or [{}])[0] or {}
|
| 281 |
+
parts = int(meta.get("parts") or 0)
|
| 282 |
+
if not parts:
|
| 283 |
+
return (res.get("documents") or [""])[0] or ""
|
| 284 |
+
version = str(meta.get("version") or "")
|
| 285 |
+
part_ids = [f"{doc_id}#{version}#{k}" for k in range(parts)]
|
| 286 |
+
got = col.get(ids=part_ids, include=["documents"])
|
| 287 |
+
by_id = dict(zip(got.get("ids") or [], got.get("documents") or []))
|
| 288 |
+
if all(pid in by_id for pid in part_ids):
|
| 289 |
+
return "".join(by_id[pid] or "" for pid in part_ids)
|
| 290 |
+
# A writer replaced the parts while we were reading; read the new manifest once more.
|
| 291 |
+
raise RuntimeError(f"Stored document {doc_id} is incomplete")
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def _write_parts(col, doc_id: str, raw: str, kind: str, extra_meta: dict | None = None) -> None:
|
| 295 |
+
"""
|
| 296 |
+
Write parts first under a new version, then switch the manifest to it in one upsert, then
|
| 297 |
+
remove the previous version's parts. A failure at any step leaves the previous version intact.
|
| 298 |
+
`extra_meta` is stored on the manifest record (e.g. the shared library's per-file details).
|
| 299 |
+
"""
|
| 300 |
+
old = col.get(ids=[doc_id], include=["metadatas"])
|
| 301 |
+
old_meta = ((old.get("metadatas") or [{}])[0] or {}) if old.get("ids") else {}
|
| 302 |
+
version = uuid.uuid4().hex[:12]
|
| 303 |
+
pieces = split_text_parts(raw)
|
| 304 |
+
part_ids = [f"{doc_id}#{version}#{k}" for k in range(len(pieces))]
|
| 305 |
+
write_records(
|
| 306 |
+
col,
|
| 307 |
+
"upsert",
|
| 308 |
+
part_ids,
|
| 309 |
+
documents=pieces,
|
| 310 |
+
embeddings=[_dummy_embedding()] * len(pieces),
|
| 311 |
+
metadatas=[{"kind": f"{kind}_part"}] * len(pieces),
|
| 312 |
+
)
|
| 313 |
+
col.upsert(
|
| 314 |
+
ids=[doc_id],
|
| 315 |
+
documents=[""],
|
| 316 |
+
embeddings=[_dummy_embedding()],
|
| 317 |
+
metadatas=[{**(extra_meta or {}), "kind": kind, "parts": len(pieces), "version": version}],
|
| 318 |
+
)
|
| 319 |
+
old_parts = int(old_meta.get("parts") or 0)
|
| 320 |
+
old_version = str(old_meta.get("version") or "")
|
| 321 |
+
if old_parts and old_version and old_version != version:
|
| 322 |
+
try:
|
| 323 |
+
delete_ids(col, [f"{doc_id}#{old_version}#{k}" for k in range(old_parts)])
|
| 324 |
+
except Exception:
|
| 325 |
+
logger.warning("Could not remove old parts of %s", doc_id, exc_info=True)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def _vfs_read_json(user_id: str, doc_id: str, default):
|
| 329 |
+
"""
|
| 330 |
+
Read one JSON document from the user's vfs collection.
|
| 331 |
+
Missing collection/document -> default. Connection or parse errors raise, so callers never
|
| 332 |
+
mistake a failed read for an empty tree and then overwrite the real one.
|
| 333 |
+
"""
|
| 334 |
+
col = _get_collection_or_none(f"user_{user_id}_vfs")
|
| 335 |
+
if col is None:
|
| 336 |
+
return default
|
| 337 |
+
raw = _read_parts(col, doc_id)
|
| 338 |
+
if not raw:
|
| 339 |
+
return default
|
| 340 |
+
data = json.loads(raw)
|
| 341 |
+
return data if isinstance(data, type(default)) else default
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def _vfs_write_json(user_id: str, doc_id: str, data, kind: str) -> None:
|
| 345 |
+
_write_parts(get_user_vfs_collection(user_id), doc_id, json.dumps(data, ensure_ascii=False), kind)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def vfs_get_tree(user_id: str) -> list:
|
| 349 |
+
return _vfs_read_json(user_id, VFS_TREE_DOC_ID, [])
|
| 350 |
|
| 351 |
|
| 352 |
def vfs_set_tree(user_id: str, tree: list) -> None:
|
| 353 |
+
_vfs_write_json(user_id, VFS_TREE_DOC_ID, tree, "vfs_tree")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 354 |
|
| 355 |
|
| 356 |
def vfs_get_file_meta_dict(user_id: str) -> dict:
|
| 357 |
+
return _vfs_read_json(user_id, VFS_FILE_META_DOC_ID, {})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
|
| 359 |
|
| 360 |
def vfs_set_file_meta_dict(user_id: str, meta: dict) -> None:
|
| 361 |
+
_vfs_write_json(user_id, VFS_FILE_META_DOC_ID, meta, "vfs_file_meta")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
|
| 363 |
|
| 364 |
+
def vfs_get_storage_version(user_id: str) -> int:
|
| 365 |
+
data = _vfs_read_json(user_id, VFS_STORAGE_VERSION_DOC_ID, {})
|
|
|
|
| 366 |
try:
|
| 367 |
+
return int(data.get("version") or 0)
|
| 368 |
+
except (TypeError, ValueError):
|
| 369 |
+
return 0
|
|
|
|
| 370 |
|
| 371 |
|
| 372 |
+
def vfs_set_storage_version(user_id: str, version: int) -> None:
|
| 373 |
+
_vfs_write_json(user_id, VFS_STORAGE_VERSION_DOC_ID, {"version": int(version)}, "vfs_storage_version")
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def delete_user_vfs_collection(user_id: str) -> bool:
|
| 377 |
+
return _delete_collection(f"user_{user_id}_vfs")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
|
| 379 |
|
| 380 |
# ---------- Users ----------
|
|
|
|
| 384 |
|
| 385 |
def user_exists_by_email(email: str) -> bool:
|
| 386 |
col = get_users_collection()
|
| 387 |
+
res = col.get(where={"email": email.lower()}, include=[])
|
| 388 |
return len(res["ids"]) > 0
|
| 389 |
|
| 390 |
|
| 391 |
+
def user_create(email: str, hashed_password: str, name: str, **extra) -> str:
|
| 392 |
user_id = str(uuid.uuid4())
|
| 393 |
col = get_users_collection()
|
| 394 |
+
meta = {
|
| 395 |
+
"email": email.lower(),
|
| 396 |
+
"hashed_password": hashed_password,
|
| 397 |
+
"name": name or email.split("@")[0],
|
| 398 |
+
"created_at": int(time.time()),
|
| 399 |
+
**extra,
|
| 400 |
+
}
|
| 401 |
+
col.add(ids=[user_id], documents=[""], metadatas=[meta], embeddings=[_dummy_embedding()])
|
| 402 |
return user_id
|
| 403 |
|
| 404 |
|
| 405 |
+
def _user_from_result(res, with_password: bool) -> dict | None:
|
|
|
|
|
|
|
| 406 |
if not res["ids"]:
|
| 407 |
return None
|
| 408 |
+
meta = res["metadatas"][0] or {}
|
| 409 |
+
user = {
|
| 410 |
"user_id": res["ids"][0],
|
| 411 |
+
"email": meta.get("email"),
|
| 412 |
+
"name": meta.get("name"),
|
| 413 |
+
# Preferences and bookkeeping live in the user's metadata under pref_* / other keys.
|
| 414 |
+
"meta": {k: v for k, v in meta.items() if k != "hashed_password"},
|
| 415 |
}
|
| 416 |
+
if with_password:
|
| 417 |
+
user["hashed_password"] = meta.get("hashed_password")
|
| 418 |
+
return user
|
| 419 |
|
| 420 |
|
| 421 |
+
def user_get_by_email(email: str) -> dict | None:
|
| 422 |
col = get_users_collection()
|
| 423 |
+
return _user_from_result(col.get(where={"email": email.lower()}), with_password=True)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def user_get_by_id(user_id: str, with_password: bool = False) -> dict | None:
|
| 427 |
+
"""User record, or None if it doesn't exist. Database errors raise."""
|
| 428 |
+
col = get_users_collection()
|
| 429 |
+
return _user_from_result(col.get(ids=[user_id]), with_password=with_password)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def user_update_metadata(user_id: str, **fields) -> dict:
|
| 433 |
+
"""Set some metadata fields on a user record (other fields are kept). Returns the new metadata."""
|
| 434 |
+
col = get_users_collection()
|
| 435 |
+
res = col.get(ids=[user_id], include=["metadatas"])
|
| 436 |
+
if not res["ids"]:
|
| 437 |
+
raise ValueError("User not found")
|
| 438 |
+
meta = {**(res["metadatas"][0] or {}), **fields}
|
| 439 |
+
col.update(ids=[user_id], metadatas=[meta])
|
| 440 |
+
return meta
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def user_update_password(user_id: str, hashed_password: str) -> None:
|
| 444 |
+
user_update_metadata(user_id, hashed_password=hashed_password)
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def users_where(where: dict) -> list[dict]:
|
| 448 |
+
"""Users matching a metadata filter, e.g. {"pref_reminders": 1} (password hashes left out)."""
|
| 449 |
+
res = get_all(get_users_collection(), where=where, include=["metadatas"])
|
| 450 |
+
out = []
|
| 451 |
+
for uid, meta in zip(res["ids"], res.get("metadatas") or []):
|
| 452 |
+
meta = {k: v for k, v in (meta or {}).items() if k != "hashed_password"}
|
| 453 |
+
out.append({"user_id": uid, "email": meta.get("email"), "name": meta.get("name"), "meta": meta})
|
| 454 |
+
return out
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def user_delete(user_id: str) -> None:
|
| 458 |
+
get_users_collection().delete(ids=[user_id])
|
| 459 |
|
| 460 |
|
| 461 |
# ---------- Sessions ----------
|
|
|
|
| 463 |
return _get_or_create_collection("sessions")
|
| 464 |
|
| 465 |
|
| 466 |
+
def _session_delete_expired_for_user(col, user_id: str, now: int) -> None:
|
| 467 |
+
try:
|
| 468 |
+
res = get_all(col, where={"user_id": user_id}, include=["metadatas"])
|
| 469 |
+
stale = [
|
| 470 |
+
sid
|
| 471 |
+
for sid, meta in zip(res["ids"], res.get("metadatas") or [])
|
| 472 |
+
if int((meta or {}).get("expires_at") or 0) <= now
|
| 473 |
+
]
|
| 474 |
+
delete_ids(col, stale)
|
| 475 |
+
except Exception:
|
| 476 |
+
logger.warning("Could not clean up expired sessions for %s", user_id, exc_info=True)
|
| 477 |
+
|
| 478 |
+
|
| 479 |
def session_create(user_id: str) -> str:
|
| 480 |
session_id = str(uuid.uuid4())
|
| 481 |
+
now = int(time.time())
|
| 482 |
col = get_sessions_collection()
|
| 483 |
+
_session_delete_expired_for_user(col, user_id, now)
|
| 484 |
col.add(
|
| 485 |
ids=[session_id],
|
| 486 |
documents=[""],
|
| 487 |
+
metadatas=[{"user_id": user_id, "created_at": now, "expires_at": now + SESSION_TTL_SECONDS}],
|
| 488 |
embeddings=[_dummy_embedding()],
|
| 489 |
)
|
| 490 |
return session_id
|
| 491 |
|
| 492 |
|
| 493 |
def session_get_user_id(session_id: str) -> str | None:
|
| 494 |
+
"""User id for a live session, or None if unknown/expired. Database errors raise."""
|
| 495 |
if not session_id:
|
| 496 |
return None
|
| 497 |
col = get_sessions_collection()
|
| 498 |
+
res = col.get(ids=[session_id], include=["metadatas"])
|
| 499 |
+
if not res["ids"]:
|
| 500 |
+
return None
|
| 501 |
+
meta = res["metadatas"][0] or {}
|
| 502 |
+
# Sessions created before expiry existed have no expires_at and are treated as expired.
|
| 503 |
+
if int(meta.get("expires_at") or 0) <= int(time.time()):
|
| 504 |
+
col.delete(ids=[session_id])
|
| 505 |
return None
|
| 506 |
+
return meta.get("user_id")
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def session_delete(session_id: str) -> None:
|
| 510 |
+
if not session_id:
|
| 511 |
+
return
|
| 512 |
+
get_sessions_collection().delete(ids=[session_id])
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def session_delete_all_for_user(user_id: str, keep_session_id: str | None = None) -> int:
|
| 516 |
+
"""End every session of a user (e.g. after a password change), optionally keeping one."""
|
| 517 |
+
col = get_sessions_collection()
|
| 518 |
+
ids = [sid for sid in get_all(col, where={"user_id": user_id}, include=[])["ids"] if sid != keep_session_id]
|
| 519 |
+
return delete_ids(col, ids)
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
# ---------- Password reset tokens (only a hash of the token is stored) ----------
|
| 523 |
+
def get_password_resets_collection():
|
| 524 |
+
return _get_or_create_collection("password_resets")
|
| 525 |
|
| 526 |
|
| 527 |
+
def password_reset_create(user_id: str, token: str) -> None:
|
| 528 |
+
col = get_password_resets_collection()
|
| 529 |
+
delete_ids(col, get_all(col, where={"user_id": user_id}, include=[])["ids"])
|
| 530 |
+
col.add(
|
| 531 |
+
ids=[short_id("r", token)],
|
| 532 |
+
documents=[""],
|
| 533 |
+
metadatas=[{"user_id": user_id, "expires_at": int(time.time()) + PASSWORD_RESET_TTL_SECONDS}],
|
| 534 |
+
embeddings=[_dummy_embedding()],
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def password_reset_pop_user_id(token: str) -> str | None:
|
| 539 |
+
"""Single use: the token is deleted whether or not it is still valid."""
|
| 540 |
+
if not token:
|
| 541 |
+
return None
|
| 542 |
+
col = get_password_resets_collection()
|
| 543 |
+
rid = short_id("r", token)
|
| 544 |
+
res = col.get(ids=[rid], include=["metadatas"])
|
| 545 |
+
if not res["ids"]:
|
| 546 |
+
return None
|
| 547 |
+
col.delete(ids=[rid])
|
| 548 |
+
meta = res["metadatas"][0] or {}
|
| 549 |
+
if int(meta.get("expires_at") or 0) <= int(time.time()):
|
| 550 |
+
return None
|
| 551 |
+
return meta.get("user_id") or None
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
def password_reset_delete_for_user(user_id: str) -> None:
|
| 555 |
+
col = get_password_resets_collection()
|
| 556 |
+
delete_ids(col, get_all(col, where={"user_id": user_id}, include=[])["ids"])
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
# ---------- User documents (full extracted text, stored in parts) ----------
|
| 560 |
def get_user_documents_collection():
|
| 561 |
return _get_or_create_collection("user_documents")
|
| 562 |
|
| 563 |
|
| 564 |
+
def _doc_where(user_id: str, path: str) -> dict:
|
| 565 |
+
return {"$and": [{"user_id": str(user_id)}, {"path": str(path)}]}
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def _doc_records(user_id: str, path: str, include: list[str]) -> dict:
|
| 569 |
+
"""All records for (user, path): new multi-part records and older single records alike."""
|
| 570 |
+
return get_all(get_user_documents_collection(), where=_doc_where(user_id, path), include=include)
|
| 571 |
|
| 572 |
|
| 573 |
def _truncate_utf8_bytes(text: str, max_bytes: int) -> tuple[str, int]:
|
|
|
|
| 584 |
|
| 585 |
|
| 586 |
def user_document_upsert(user_id: str, path: str, content: str, original_filename: str):
|
| 587 |
+
"""Store extracted text for a path (original PDFs/images stay on the client)."""
|
| 588 |
col = get_user_documents_collection()
|
|
|
|
| 589 |
trimmed, full_bytes = _truncate_utf8_bytes(content or "", USER_DOCUMENT_MAX_BYTES)
|
| 590 |
stored_bytes = len((trimmed or "").encode("utf-8"))
|
| 591 |
+
pieces = split_text_parts(trimmed)
|
| 592 |
+
base = short_id("d", user_id, path)
|
| 593 |
+
ids = [f"{base}_{k}" for k in range(len(pieces))]
|
| 594 |
+
meta = {
|
| 595 |
+
"user_id": str(user_id),
|
| 596 |
+
"path": str(path or ""),
|
| 597 |
+
"original_filename": str(original_filename or ""),
|
| 598 |
+
"truncated": int(stored_bytes < full_bytes),
|
| 599 |
+
"content_bytes": int(full_bytes),
|
| 600 |
+
"stored_bytes": int(stored_bytes),
|
| 601 |
+
"parts": len(pieces),
|
| 602 |
+
}
|
| 603 |
+
stale = [rid for rid in _doc_records(user_id, path, include=[])["ids"] if rid not in set(ids)]
|
| 604 |
+
write_records(
|
| 605 |
+
col,
|
| 606 |
+
"upsert",
|
| 607 |
+
ids,
|
| 608 |
+
documents=pieces,
|
| 609 |
+
embeddings=[_dummy_embedding()] * len(pieces),
|
| 610 |
+
metadatas=[{**meta, "part": k} for k in range(len(pieces))],
|
| 611 |
)
|
| 612 |
+
delete_ids(col, stale)
|
| 613 |
|
| 614 |
|
| 615 |
+
def user_document_get(user_id: str, path: str) -> dict | None:
|
| 616 |
+
"""{"content", "truncated", "original_filename"} for a path, or None if nothing is stored."""
|
| 617 |
+
res = _doc_records(user_id, path, include=["documents", "metadatas"])
|
|
|
|
| 618 |
if not res["ids"]:
|
| 619 |
+
return None
|
| 620 |
+
rows = sorted(
|
| 621 |
+
zip(res.get("documents") or [], res.get("metadatas") or []),
|
| 622 |
+
key=lambda r: int((r[1] or {}).get("part") or 0),
|
| 623 |
+
)
|
| 624 |
+
first = rows[0][1] or {}
|
| 625 |
+
return {
|
| 626 |
+
"content": "".join(doc or "" for doc, _ in rows),
|
| 627 |
+
"truncated": bool(int(first.get("truncated") or 0)),
|
| 628 |
+
"original_filename": first.get("original_filename") or "",
|
| 629 |
+
}
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
def user_document_get_content(user_id: str, path: str) -> str | None:
|
| 633 |
+
doc = user_document_get(user_id, path)
|
| 634 |
+
return doc["content"] if doc else None
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def user_document_exists(user_id: str, path: str) -> bool:
|
| 638 |
+
"""True if extracted text is stored for this path. Database errors raise."""
|
| 639 |
+
return bool(_doc_records(user_id, path, include=[])["ids"])
|
| 640 |
|
| 641 |
|
| 642 |
def user_document_delete_by_path(user_id: str, path: str):
|
|
|
|
| 643 |
col = get_user_documents_collection()
|
| 644 |
+
delete_ids(col, _doc_records(user_id, path, include=[])["ids"])
|
|
|
|
|
|
|
|
|
|
| 645 |
|
| 646 |
|
| 647 |
+
def user_document_delete_many(user_id: str, path_filter=None):
|
| 648 |
+
"""Delete documents for user_id. path_filter: if callable(path) -> bool, only delete matching paths."""
|
| 649 |
col = get_user_documents_collection()
|
| 650 |
+
res = get_all(col, where={"user_id": str(user_id)}, include=["metadatas"])
|
| 651 |
+
ids_to_delete = [
|
| 652 |
+
doc_id
|
| 653 |
+
for doc_id, meta in zip(res["ids"], res.get("metadatas") or [])
|
| 654 |
+
if path_filter is None or path_filter((meta or {}).get("path", ""))
|
| 655 |
+
]
|
| 656 |
+
delete_ids(col, ids_to_delete)
|
|
|
|
|
|
|
| 657 |
|
| 658 |
|
| 659 |
def user_documents_relocate_prefix(user_id: str, old_prefix: str, new_prefix: str) -> int:
|
| 660 |
"""Rename stored document paths under old_prefix to new_prefix (longest paths first)."""
|
| 661 |
col = get_user_documents_collection()
|
| 662 |
+
res = get_all(col, where={"user_id": str(user_id)}, include=["metadatas"])
|
| 663 |
+
paths: set[str] = set()
|
| 664 |
+
for m in res.get("metadatas") or []:
|
|
|
|
| 665 |
p = ((m or {}).get("path") or "").replace("\\", "/")
|
| 666 |
+
if p == old_prefix or p.startswith(old_prefix + "/"):
|
| 667 |
+
paths.add(p)
|
| 668 |
+
pairs = sorted(((p, new_prefix + p[len(old_prefix) :]) for p in paths), key=lambda x: -len(x[0]))
|
|
|
|
|
|
|
| 669 |
n = 0
|
| 670 |
for op, np in pairs:
|
| 671 |
if op != np and user_document_rename_path(user_id, op, np):
|
|
|
|
| 675 |
|
| 676 |
def user_document_rename_path(user_id: str, old_path: str, new_path: str) -> bool:
|
| 677 |
"""Move stored extracted text from old_path to new_path."""
|
| 678 |
+
doc = user_document_get(user_id, old_path)
|
| 679 |
+
if doc is None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 680 |
return False
|
| 681 |
+
ofn = doc["original_filename"] or os.path.basename(new_path.replace("\\", "/"))
|
| 682 |
+
user_document_upsert(user_id, new_path, doc["content"], ofn)
|
| 683 |
+
user_document_delete_by_path(user_id, old_path)
|
| 684 |
+
return True
|
| 685 |
|
| 686 |
|
| 687 |
# ---------- OneNote OAuth tokens/state ----------
|
|
|
|
| 727 |
return None
|
| 728 |
return user_id
|
| 729 |
except Exception:
|
| 730 |
+
logger.warning("OneNote OAuth state lookup failed", exc_info=True)
|
| 731 |
return None
|
| 732 |
|
| 733 |
|
|
|
|
| 762 |
data = json.loads(raw)
|
| 763 |
return data if isinstance(data, dict) else None
|
| 764 |
except Exception:
|
| 765 |
+
logger.warning("OneNote token lookup failed for %s", user_id, exc_info=True)
|
| 766 |
return None
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
def onenote_token_delete(user_id: str) -> None:
|
| 770 |
+
get_onenote_tokens_collection().delete(ids=[str(user_id)])
|
backend/deps.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FastAPI dependencies for resolving the caller."""
|
| 2 |
+
from typing import Annotated
|
| 3 |
+
|
| 4 |
+
from fastapi import Depends, HTTPException, Request
|
| 5 |
+
|
| 6 |
+
from backend.auth import get_effective_user, require_signed_in_user
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def get_effective_user_dep(request: Request) -> tuple[str, bool]:
|
| 10 |
+
try:
|
| 11 |
+
return get_effective_user(request)
|
| 12 |
+
except ValueError as e:
|
| 13 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# Routes that store data or call paid AI services (OCR, chat, study tools) need an account.
|
| 17 |
+
SignedInUser = Annotated[str, Depends(require_signed_in_user)]
|
| 18 |
+
EffectiveUser = Annotated[tuple[str, bool], Depends(get_effective_user_dep)]
|
backend/extract_api.py
CHANGED
|
@@ -1,80 +1,10 @@
|
|
| 1 |
-
"""
|
| 2 |
-
import
|
|
|
|
| 3 |
from PIL import Image
|
| 4 |
import pytesseract
|
| 5 |
-
import fitz # PyMuPDF
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
def extract_text_from_pdf_bytes(pdf_bytes: bytes) -> str:
|
| 9 |
-
"""Extract text from PDF bytes in memory. Does not write to disk."""
|
| 10 |
-
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
|
| 11 |
-
try:
|
| 12 |
-
text = ""
|
| 13 |
-
for page in doc:
|
| 14 |
-
text += page.get_text()
|
| 15 |
-
return text
|
| 16 |
-
finally:
|
| 17 |
-
doc.close()
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def extract_text(notes_root: str, subject: str):
|
| 21 |
-
"""
|
| 22 |
-
Extract text from PDFs and images in notes_root/subject.
|
| 23 |
-
Saves .txt files next to originals. Returns extracted content for saving to MongoDB.
|
| 24 |
-
"""
|
| 25 |
-
folder_path = os.path.join(notes_root, subject)
|
| 26 |
-
if not os.path.exists(folder_path):
|
| 27 |
-
return {"error": "Folder does not exist.", "processed_files": [], "extracted_texts": {}}
|
| 28 |
-
|
| 29 |
-
extracted = {}
|
| 30 |
-
processed_files = []
|
| 31 |
-
|
| 32 |
-
for fname in os.listdir(folder_path):
|
| 33 |
-
fpath = os.path.join(folder_path, fname)
|
| 34 |
-
if os.path.isfile(fpath):
|
| 35 |
-
try:
|
| 36 |
-
if fname.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tiff')):
|
| 37 |
-
print(f"🔄 Extracting text from image: {fname}")
|
| 38 |
-
text = pytesseract.image_to_string(Image.open(fpath))
|
| 39 |
-
extracted[fname] = text
|
| 40 |
-
elif fname.lower().endswith('.pdf'):
|
| 41 |
-
print(f"🔄 Extracting text from PDF: {fname}")
|
| 42 |
-
pdf = fitz.open(fpath)
|
| 43 |
-
pdf_text = ""
|
| 44 |
-
for page in pdf:
|
| 45 |
-
pdf_text += page.get_text()
|
| 46 |
-
pdf.close()
|
| 47 |
-
extracted[fname] = pdf_text
|
| 48 |
-
else:
|
| 49 |
-
print(f"⚠️ Skipping unsupported file: {fname}")
|
| 50 |
-
continue
|
| 51 |
-
|
| 52 |
-
# Save extracted text to .txt file (local only; DB is updated by caller)
|
| 53 |
-
txt_filename = os.path.splitext(fname)[0] + ".txt"
|
| 54 |
-
txt_path = os.path.join(folder_path, txt_filename)
|
| 55 |
-
with open(txt_path, "w", encoding="utf-8") as f:
|
| 56 |
-
f.write(extracted[fname])
|
| 57 |
-
|
| 58 |
-
processed_files.append({
|
| 59 |
-
"original_file": fname,
|
| 60 |
-
"text_file": txt_filename,
|
| 61 |
-
"text_length": len(extracted[fname]),
|
| 62 |
-
})
|
| 63 |
-
print(f"✅ Saved text to {txt_filename}")
|
| 64 |
-
|
| 65 |
-
except Exception as e:
|
| 66 |
-
print(f"❌ Error processing {fname}: {str(e)}")
|
| 67 |
-
continue
|
| 68 |
-
|
| 69 |
-
return {
|
| 70 |
-
"message": f"Extracted text from {len(processed_files)} files",
|
| 71 |
-
"processed_files": processed_files,
|
| 72 |
-
"extracted_texts": extracted,
|
| 73 |
-
}
|
| 74 |
|
| 75 |
|
| 76 |
def extract_text_from_image_bytes(data: bytes) -> str:
|
| 77 |
-
import io
|
| 78 |
img = Image.open(io.BytesIO(data))
|
| 79 |
return pytesseract.image_to_string(img)
|
| 80 |
-
|
|
|
|
| 1 |
+
"""Local text extraction from images (fallback when Sarvam Vision is unavailable). PDFs: see pages.py."""
|
| 2 |
+
import io
|
| 3 |
+
|
| 4 |
from PIL import Image
|
| 5 |
import pytesseract
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
|
| 8 |
def extract_text_from_image_bytes(data: bytes) -> str:
|
|
|
|
| 9 |
img = Image.open(io.BytesIO(data))
|
| 10 |
return pytesseract.image_to_string(img)
|
|
|
backend/feedback.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Answer ratings and general feedback from students, stored in the `feedback` collection."""
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import uuid
|
| 5 |
+
|
| 6 |
+
from backend.chroma_store import _dummy_embedding, _get_or_create_collection, delete_ids, get_all
|
| 7 |
+
|
| 8 |
+
KINDS = ("answer", "general")
|
| 9 |
+
RATINGS = ("up", "down", "")
|
| 10 |
+
_FIELD_LIMITS = {"comment": 2000, "question": 1000, "answer": 2000, "sources": 1000}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _collection():
|
| 14 |
+
return _get_or_create_collection("feedback")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def add(user_id: str, kind: str, rating: str, selection_stage: str = "", **fields: str) -> None:
|
| 18 |
+
doc = {k: str(fields.get(k) or "")[:limit] for k, limit in _FIELD_LIMITS.items()} # stays well under 16 KB
|
| 19 |
+
_collection().add(
|
| 20 |
+
ids=[f"fb_{uuid.uuid4().hex}"],
|
| 21 |
+
documents=[json.dumps(doc, ensure_ascii=False)],
|
| 22 |
+
embeddings=[_dummy_embedding()],
|
| 23 |
+
metadatas=[{
|
| 24 |
+
"user_id": user_id,
|
| 25 |
+
"kind": kind,
|
| 26 |
+
"rating": rating,
|
| 27 |
+
"selection_stage": (selection_stage or "")[:40],
|
| 28 |
+
"created_at": int(time.time()),
|
| 29 |
+
}],
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def recent(limit: int = 50, since: int = 0) -> list[dict]:
|
| 34 |
+
res = get_all(_collection(), where={"created_at": {"$gte": int(since)}}, include=["documents", "metadatas"])
|
| 35 |
+
rows = []
|
| 36 |
+
for doc, meta in zip(res.get("documents") or [], res.get("metadatas") or []):
|
| 37 |
+
meta = meta or {}
|
| 38 |
+
rows.append({**json.loads(doc or "{}"), **{k: meta.get(k) for k in ("user_id", "kind", "rating", "selection_stage", "created_at")}})
|
| 39 |
+
rows.sort(key=lambda r: r.get("created_at") or 0, reverse=True)
|
| 40 |
+
return rows[:limit]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def delete_user(user_id: str) -> None:
|
| 44 |
+
col = _collection()
|
| 45 |
+
delete_ids(col, get_all(col, where={"user_id": user_id}, include=[])["ids"])
|
backend/file_meta.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
"""Per-user file metadata (primary authority, related paths) stored in ChromaDB (vfs collection)."""
|
| 2 |
from typing import Any
|
| 3 |
|
| 4 |
-
from backend.chroma_store import vfs_get_file_meta_dict, vfs_set_file_meta_dict
|
| 5 |
|
| 6 |
|
| 7 |
def load_file_meta(user_id: str) -> dict[str, dict[str, Any]]:
|
|
@@ -20,101 +20,69 @@ def get_entry(user_id: str, rel_path: str) -> dict[str, Any]:
|
|
| 20 |
|
| 21 |
def set_entry(user_id: str, rel_path: str, **fields) -> dict[str, Any]:
|
| 22 |
rel_path = rel_path.replace("\\", "/").strip("/")
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
| 32 |
return cur
|
| 33 |
|
| 34 |
|
| 35 |
def delete_keys_for_prefix(user_id: str, folder_prefix: str) -> None:
|
| 36 |
folder_prefix = folder_prefix.replace("\\", "/").strip("/")
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
def delete_key(user_id: str, rel_path: str) -> None:
|
| 45 |
-
rel_path = rel_path.replace("\\", "/").strip("/")
|
| 46 |
-
meta = load_file_meta(user_id)
|
| 47 |
-
if rel_path in meta:
|
| 48 |
-
del meta[rel_path]
|
| 49 |
save_file_meta(user_id, meta)
|
| 50 |
|
| 51 |
|
| 52 |
-
def
|
| 53 |
-
"""Chroma `path` values to update when user toggles metadata on this file."""
|
| 54 |
-
import os
|
| 55 |
-
|
| 56 |
rel_path = rel_path.replace("\\", "/").strip("/")
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
out.append(base)
|
| 63 |
-
return list(dict.fromkeys(out))
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
def merged_meta_for_chunk(
|
| 67 |
-
user_id: str,
|
| 68 |
-
chunk_path: str,
|
| 69 |
-
source_file: str,
|
| 70 |
-
) -> dict[str, Any]:
|
| 71 |
-
"""Resolve file_meta for a chunk: try chunk path, .pdf/.txt sibling, and image→txt."""
|
| 72 |
-
import os
|
| 73 |
-
|
| 74 |
-
chunk_path = chunk_path.replace("\\", "/")
|
| 75 |
-
meta = load_file_meta(user_id)
|
| 76 |
-
candidates = [chunk_path]
|
| 77 |
-
base, ext = os.path.splitext(chunk_path)
|
| 78 |
-
ext_l = ext.lower()
|
| 79 |
-
if ext_l == ".txt":
|
| 80 |
-
for img_ext in (".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tiff"):
|
| 81 |
-
candidates.append(base + img_ext)
|
| 82 |
-
if base:
|
| 83 |
-
candidates.append(base + ".pdf")
|
| 84 |
-
elif ext_l == ".pdf":
|
| 85 |
-
candidates.append(base + ".txt")
|
| 86 |
-
for c in candidates:
|
| 87 |
-
c = c.strip("/")
|
| 88 |
-
if c in meta:
|
| 89 |
-
return dict(meta[c])
|
| 90 |
-
return {}
|
| 91 |
|
| 92 |
|
| 93 |
def file_meta_rename_path(user_id: str, old_p: str, new_p: str) -> None:
|
| 94 |
old_p = old_p.replace("\\", "/").strip("/")
|
| 95 |
new_p = new_p.replace("\\", "/").strip("/")
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
| 101 |
|
| 102 |
|
| 103 |
def file_meta_relocate_prefix(user_id: str, old_prefix: str, new_prefix: str) -> None:
|
| 104 |
old_prefix = old_prefix.replace("\\", "/").strip("/")
|
| 105 |
new_prefix = new_prefix.replace("\\", "/").strip("/")
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
if
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
|
| 120 |
def course_id_from_path(rel_path: str) -> str:
|
|
|
|
| 1 |
"""Per-user file metadata (primary authority, related paths) stored in ChromaDB (vfs collection)."""
|
| 2 |
from typing import Any
|
| 3 |
|
| 4 |
+
from backend.chroma_store import user_lock, vfs_get_file_meta_dict, vfs_set_file_meta_dict
|
| 5 |
|
| 6 |
|
| 7 |
def load_file_meta(user_id: str) -> dict[str, dict[str, Any]]:
|
|
|
|
| 20 |
|
| 21 |
def set_entry(user_id: str, rel_path: str, **fields) -> dict[str, Any]:
|
| 22 |
rel_path = rel_path.replace("\\", "/").strip("/")
|
| 23 |
+
with user_lock(user_id):
|
| 24 |
+
meta = load_file_meta(user_id)
|
| 25 |
+
cur = dict(meta.get(rel_path) or {})
|
| 26 |
+
for k, v in fields.items():
|
| 27 |
+
if v is None:
|
| 28 |
+
cur.pop(k, None)
|
| 29 |
+
else:
|
| 30 |
+
cur[k] = v
|
| 31 |
+
meta[rel_path] = cur
|
| 32 |
+
save_file_meta(user_id, meta)
|
| 33 |
return cur
|
| 34 |
|
| 35 |
|
| 36 |
def delete_keys_for_prefix(user_id: str, folder_prefix: str) -> None:
|
| 37 |
folder_prefix = folder_prefix.replace("\\", "/").strip("/")
|
| 38 |
+
with user_lock(user_id):
|
| 39 |
+
meta = load_file_meta(user_id)
|
| 40 |
+
keys = [k for k in meta if k == folder_prefix or k.startswith(folder_prefix + "/")]
|
| 41 |
+
if not keys:
|
| 42 |
+
return
|
| 43 |
+
for k in keys:
|
| 44 |
+
del meta[k]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
save_file_meta(user_id, meta)
|
| 46 |
|
| 47 |
|
| 48 |
+
def delete_key(user_id: str, rel_path: str) -> None:
|
|
|
|
|
|
|
|
|
|
| 49 |
rel_path = rel_path.replace("\\", "/").strip("/")
|
| 50 |
+
with user_lock(user_id):
|
| 51 |
+
meta = load_file_meta(user_id)
|
| 52 |
+
if rel_path in meta:
|
| 53 |
+
del meta[rel_path]
|
| 54 |
+
save_file_meta(user_id, meta)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
|
| 57 |
def file_meta_rename_path(user_id: str, old_p: str, new_p: str) -> None:
|
| 58 |
old_p = old_p.replace("\\", "/").strip("/")
|
| 59 |
new_p = new_p.replace("\\", "/").strip("/")
|
| 60 |
+
with user_lock(user_id):
|
| 61 |
+
meta = load_file_meta(user_id)
|
| 62 |
+
if old_p not in meta:
|
| 63 |
+
return
|
| 64 |
+
meta[new_p] = meta.pop(old_p)
|
| 65 |
+
save_file_meta(user_id, meta)
|
| 66 |
|
| 67 |
|
| 68 |
def file_meta_relocate_prefix(user_id: str, old_prefix: str, new_prefix: str) -> None:
|
| 69 |
old_prefix = old_prefix.replace("\\", "/").strip("/")
|
| 70 |
new_prefix = new_prefix.replace("\\", "/").strip("/")
|
| 71 |
+
with user_lock(user_id):
|
| 72 |
+
meta = load_file_meta(user_id)
|
| 73 |
+
keys = sorted(
|
| 74 |
+
[k for k in meta if k == old_prefix or k.startswith(old_prefix + "/")],
|
| 75 |
+
key=lambda x: -len(x),
|
| 76 |
+
)
|
| 77 |
+
if not keys:
|
| 78 |
+
return
|
| 79 |
+
for k in keys:
|
| 80 |
+
if k == old_prefix:
|
| 81 |
+
nk = new_prefix
|
| 82 |
+
else:
|
| 83 |
+
nk = new_prefix + "/" + k[len(old_prefix) + 1 :]
|
| 84 |
+
meta[nk] = meta.pop(k)
|
| 85 |
+
save_file_meta(user_id, meta)
|
| 86 |
|
| 87 |
|
| 88 |
def course_id_from_path(rel_path: str) -> str:
|
backend/ingest_api.py
CHANGED
|
@@ -1,14 +1,45 @@
|
|
| 1 |
"""Ingest text into ChromaDB using the centralized client and per-user collection (user_{user_id}_notes)."""
|
|
|
|
| 2 |
import os
|
|
|
|
|
|
|
| 3 |
from sentence_transformers import SentenceTransformer
|
| 4 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 5 |
|
| 6 |
-
from backend.chroma_store import
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
CHUNK_SIZE = 750
|
| 10 |
CHUNK_OVERLAP = 100
|
| 11 |
BATCH_SIZE = 50
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
def _chunk_text(text: str):
|
|
@@ -16,8 +47,26 @@ def _chunk_text(text: str):
|
|
| 16 |
return splitter.split_text(text)
|
| 17 |
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
def _base_metadata_user(user_id: str, path: str, source_file: str) -> dict:
|
| 20 |
-
fm =
|
| 21 |
# Chroma metadata: str, int, float, bool — use int flags for broad server/Cloud compatibility.
|
| 22 |
return {
|
| 23 |
"user_id": str(user_id),
|
|
@@ -29,25 +78,26 @@ def _base_metadata_user(user_id: str, path: str, source_file: str) -> dict:
|
|
| 29 |
}
|
| 30 |
|
| 31 |
|
| 32 |
-
def _add_chunks_to_collection(collection, chunks: list, path: str, source_file: str,
|
| 33 |
-
"""
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
except Exception:
|
| 39 |
-
pass
|
| 40 |
-
path_safe = path.replace("|", "\x00")
|
| 41 |
for i in range(0, len(chunks), BATCH_SIZE):
|
| 42 |
batch = chunks[i : i + BATCH_SIZE]
|
| 43 |
-
embeddings =
|
| 44 |
-
ids =
|
| 45 |
metadatas = []
|
| 46 |
-
for j
|
| 47 |
-
m =
|
| 48 |
-
|
|
|
|
| 49 |
metadatas.append(m)
|
| 50 |
-
collection.
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
|
| 53 |
def refresh_metadata_for_paths(user_id: str, chroma_paths: list[str]) -> int:
|
|
@@ -58,115 +108,56 @@ def refresh_metadata_for_paths(user_id: str, chroma_paths: list[str]) -> int:
|
|
| 58 |
updated = 0
|
| 59 |
for path in chroma_paths:
|
| 60 |
try:
|
| 61 |
-
res =
|
| 62 |
-
ids = res
|
| 63 |
if not ids:
|
| 64 |
continue
|
| 65 |
metas = []
|
| 66 |
for old in res.get("metadatas") or []:
|
| 67 |
old = old or {}
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
nm = _base_metadata_user(user_id, p, sf)
|
| 71 |
-
if "chunk_index" in old:
|
| 72 |
-
nm["chunk_index"] = old["chunk_index"]
|
| 73 |
metas.append(nm)
|
| 74 |
-
col
|
| 75 |
updated += len(ids)
|
| 76 |
except Exception:
|
|
|
|
| 77 |
continue
|
| 78 |
return updated
|
| 79 |
|
| 80 |
|
| 81 |
-
def
|
| 82 |
-
"""
|
| 83 |
-
Read PDF from bytes, extract text in memory, chunk (~750 chars, ~100 overlap), and add to
|
| 84 |
-
the user's ChromaDB collection. Does not write any file to disk.
|
| 85 |
-
"""
|
| 86 |
-
from backend.extract_api import extract_text_from_pdf_bytes
|
| 87 |
-
|
| 88 |
-
_ = notes_root # unused; kept for call-site compatibility
|
| 89 |
-
text = extract_text_from_pdf_bytes(pdf_bytes)
|
| 90 |
-
if not text or not text.strip():
|
| 91 |
-
return {"chunks_created": 0, "message": "No text extracted from PDF."}
|
| 92 |
-
collection = get_user_collection(user_id)
|
| 93 |
-
model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 94 |
-
chunks = _chunk_text(text)
|
| 95 |
-
_add_chunks_to_collection(collection, chunks, rel_path, filename, model, user_id)
|
| 96 |
-
return {"chunks_created": len(chunks), "message": f"Ingested {len(chunks)} chunks from PDF."}
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
def ingest_folder(notes_root: str, user_id: str, subject: str):
|
| 100 |
-
"""Ingest all text files from notes_root/subject into the user's ChromaDB collection."""
|
| 101 |
-
folder_path = os.path.join(notes_root, subject)
|
| 102 |
-
if not os.path.exists(folder_path):
|
| 103 |
-
return {"error": "Folder does not exist.", "chunks_created": 0}
|
| 104 |
-
|
| 105 |
-
items = []
|
| 106 |
-
for fname in os.listdir(folder_path):
|
| 107 |
-
if not fname.endswith(".txt"):
|
| 108 |
-
continue
|
| 109 |
-
txt_path = os.path.join(folder_path, fname)
|
| 110 |
-
try:
|
| 111 |
-
with open(txt_path, "r", encoding="utf-8") as f:
|
| 112 |
-
text = f.read()
|
| 113 |
-
if text.strip():
|
| 114 |
-
rel_path = os.path.join(subject, fname).replace("\\", "/")
|
| 115 |
-
items.append((rel_path, fname, text))
|
| 116 |
-
except OSError as e:
|
| 117 |
-
print(f"❌ Error reading {fname}: {str(e)}")
|
| 118 |
-
continue
|
| 119 |
-
|
| 120 |
-
if not items:
|
| 121 |
-
return {"error": "No extracted text found in folder.", "chunks_created": 0}
|
| 122 |
-
|
| 123 |
-
collection = get_user_collection(user_id)
|
| 124 |
-
model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 125 |
-
total_chunks = 0
|
| 126 |
-
for rel_path, source_file, text in items:
|
| 127 |
-
chunks = _chunk_text(text)
|
| 128 |
-
_add_chunks_to_collection(collection, chunks, rel_path, source_file, model, user_id)
|
| 129 |
-
total_chunks += len(chunks)
|
| 130 |
-
return {
|
| 131 |
-
"message": f"Ingested {total_chunks} chunks for subject '{subject}' into ChromaDB.",
|
| 132 |
-
"chunks_created": total_chunks,
|
| 133 |
-
"files_processed": [x[1] for x in items],
|
| 134 |
-
"final_count": collection.count(),
|
| 135 |
-
}
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
def ingest_text_for_path(user_id: str, rel_path: str, source_file: str, text: str):
|
| 139 |
"""Ingest or replace chunks for a single extracted text path (e.g. after vision OCR)."""
|
| 140 |
if not text or not text.strip():
|
| 141 |
return {"chunks_created": 0, "message": "Empty text."}
|
| 142 |
collection = get_user_collection(user_id)
|
| 143 |
-
|
| 144 |
-
chunks
|
| 145 |
-
_add_chunks_to_collection(collection, chunks, rel_path, source_file, model, user_id)
|
| 146 |
return {"chunks_created": len(chunks), "message": f"Ingested {len(chunks)} chunks."}
|
| 147 |
|
| 148 |
|
| 149 |
def chunks_relocate_path(user_id: str, old_path: str, new_path: str, source_file: str | None = None) -> int:
|
| 150 |
"""Move all chunks from old_path to new_path (same text and embeddings, updated metadata)."""
|
| 151 |
col = get_user_collection(user_id)
|
| 152 |
-
res =
|
| 153 |
docs = res.get("documents") or []
|
| 154 |
-
ids = res
|
| 155 |
if not ids:
|
| 156 |
return 0
|
| 157 |
embs = res.get("embeddings")
|
| 158 |
-
model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 159 |
if embs is None or len(embs) != len(docs):
|
| 160 |
-
embs =
|
| 161 |
else:
|
| 162 |
-
embs = list(
|
| 163 |
-
col.delete(ids=ids)
|
| 164 |
sf = source_file or os.path.basename(new_path.replace("\\", "/"))
|
|
|
|
| 165 |
old_metas = res.get("metadatas") or []
|
| 166 |
metadatas = []
|
| 167 |
for k in range(len(docs)):
|
| 168 |
-
m =
|
| 169 |
om = old_metas[k] if k < len(old_metas) else {}
|
|
|
|
|
|
|
| 170 |
if isinstance(om, dict) and "chunk_index" in om:
|
| 171 |
try:
|
| 172 |
m["chunk_index"] = int(om["chunk_index"])
|
|
@@ -175,35 +166,20 @@ def chunks_relocate_path(user_id: str, old_path: str, new_path: str, source_file
|
|
| 175 |
else:
|
| 176 |
m["chunk_index"] = k
|
| 177 |
metadatas.append(m)
|
| 178 |
-
|
| 179 |
-
new_ids =
|
| 180 |
-
|
|
|
|
|
|
|
| 181 |
return len(docs)
|
| 182 |
|
| 183 |
|
| 184 |
-
def
|
| 185 |
-
"""
|
| 186 |
old_prefix = old_prefix.replace("\\", "/").strip("/")
|
| 187 |
new_prefix = new_prefix.replace("\\", "/").strip("/")
|
| 188 |
-
col = get_user_collection(user_id)
|
| 189 |
-
res = col.get(include=["metadatas"])
|
| 190 |
-
metas = res.get("metadatas") or []
|
| 191 |
-
paths = {((m or {}).get("path") or "").replace("\\", "/") for m in metas if (m or {}).get("path")}
|
| 192 |
-
todo: list[tuple[str, str]] = []
|
| 193 |
-
for p in paths:
|
| 194 |
-
if p == old_prefix:
|
| 195 |
-
todo.append((p, new_prefix))
|
| 196 |
-
elif p.startswith(old_prefix + "/"):
|
| 197 |
-
todo.append((p, new_prefix + p[len(old_prefix) :]))
|
| 198 |
-
todo.sort(key=lambda x: -len(x[0]))
|
| 199 |
moved = 0
|
| 200 |
-
for
|
| 201 |
-
if
|
| 202 |
-
|
| 203 |
-
sf = None
|
| 204 |
-
for m in metas:
|
| 205 |
-
if ((m or {}).get("path") or "").replace("\\", "/") == old_p:
|
| 206 |
-
sf = (m or {}).get("source_file")
|
| 207 |
-
break
|
| 208 |
-
moved += chunks_relocate_path(user_id, old_p, new_p, sf)
|
| 209 |
return moved
|
|
|
|
| 1 |
"""Ingest text into ChromaDB using the centralized client and per-user collection (user_{user_id}_notes)."""
|
| 2 |
+
import logging
|
| 3 |
import os
|
| 4 |
+
import threading
|
| 5 |
+
|
| 6 |
from sentence_transformers import SentenceTransformer
|
| 7 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 8 |
|
| 9 |
+
from backend.chroma_store import (
|
| 10 |
+
chunk_ids_for_path,
|
| 11 |
+
delete_ids,
|
| 12 |
+
get_all,
|
| 13 |
+
get_user_collection,
|
| 14 |
+
write_records,
|
| 15 |
+
)
|
| 16 |
+
from backend.file_meta import course_id_from_path, get_entry
|
| 17 |
+
from backend.pages import page_at
|
| 18 |
|
| 19 |
CHUNK_SIZE = 750
|
| 20 |
CHUNK_OVERLAP = 100
|
| 21 |
BATCH_SIZE = 50
|
| 22 |
+
EMBED_MODEL_NAME = "all-MiniLM-L6-v2"
|
| 23 |
+
|
| 24 |
+
logger = logging.getLogger(__name__)
|
| 25 |
+
|
| 26 |
+
_embedder = None
|
| 27 |
+
_embedder_lock = threading.Lock()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def get_embedder() -> SentenceTransformer:
|
| 31 |
+
"""Load the embedding model once per process and reuse it (loading takes seconds)."""
|
| 32 |
+
global _embedder
|
| 33 |
+
if _embedder is None:
|
| 34 |
+
with _embedder_lock:
|
| 35 |
+
if _embedder is None:
|
| 36 |
+
_embedder = SentenceTransformer(EMBED_MODEL_NAME)
|
| 37 |
+
return _embedder
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def embed_texts(texts: list[str]):
|
| 41 |
+
"""Unit-length embeddings (numpy array, one row per text)."""
|
| 42 |
+
return get_embedder().encode(list(texts), normalize_embeddings=True)
|
| 43 |
|
| 44 |
|
| 45 |
def _chunk_text(text: str):
|
|
|
|
| 47 |
return splitter.split_text(text)
|
| 48 |
|
| 49 |
|
| 50 |
+
def _chunk_text_with_pages(text: str, page_starts) -> tuple[list[str], list[int | None]]:
|
| 51 |
+
"""Chunks plus the page each chunk starts on (None when the text has no page information)."""
|
| 52 |
+
if not page_starts:
|
| 53 |
+
chunks = _chunk_text(text)
|
| 54 |
+
return chunks, [None] * len(chunks)
|
| 55 |
+
splitter = RecursiveCharacterTextSplitter(
|
| 56 |
+
chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP, add_start_index=True
|
| 57 |
+
)
|
| 58 |
+
docs = splitter.create_documents([text])
|
| 59 |
+
return (
|
| 60 |
+
[d.page_content for d in docs],
|
| 61 |
+
[page_at(int(d.metadata.get("start_index") or 0), page_starts) for d in docs],
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
# Chunk metadata that belongs to the chunk itself (kept when a file is moved or re-labelled).
|
| 65 |
+
_CHUNK_KEYS = ("chunk_index", "page")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
def _base_metadata_user(user_id: str, path: str, source_file: str) -> dict:
|
| 69 |
+
fm = get_entry(user_id, path)
|
| 70 |
# Chroma metadata: str, int, float, bool — use int flags for broad server/Cloud compatibility.
|
| 71 |
return {
|
| 72 |
"user_id": str(user_id),
|
|
|
|
| 78 |
}
|
| 79 |
|
| 80 |
|
| 81 |
+
def _add_chunks_to_collection(collection, chunks: list, path: str, source_file: str, user_id: str, pages=None):
|
| 82 |
+
"""Replace the chunks stored for `path` with new text, embeddings, and metadata."""
|
| 83 |
+
old_ids = get_all(collection, where={"path": path}, include=[])["ids"]
|
| 84 |
+
base_meta = _base_metadata_user(user_id, path, source_file)
|
| 85 |
+
new_ids: list[str] = []
|
| 86 |
+
# Write the new chunks first, then drop leftovers, so a failure never leaves the file empty.
|
|
|
|
|
|
|
|
|
|
| 87 |
for i in range(0, len(chunks), BATCH_SIZE):
|
| 88 |
batch = chunks[i : i + BATCH_SIZE]
|
| 89 |
+
embeddings = embed_texts(batch).tolist()
|
| 90 |
+
ids = chunk_ids_for_path(path, len(batch), start=i)
|
| 91 |
metadatas = []
|
| 92 |
+
for j in range(len(batch)):
|
| 93 |
+
m = {**base_meta, "chunk_index": i + j}
|
| 94 |
+
if pages and pages[i + j] is not None:
|
| 95 |
+
m["page"] = int(pages[i + j])
|
| 96 |
metadatas.append(m)
|
| 97 |
+
collection.upsert(documents=batch, embeddings=embeddings, ids=ids, metadatas=metadatas)
|
| 98 |
+
new_ids.extend(ids)
|
| 99 |
+
keep = set(new_ids)
|
| 100 |
+
delete_ids(collection, [i for i in old_ids if i not in keep])
|
| 101 |
|
| 102 |
|
| 103 |
def refresh_metadata_for_paths(user_id: str, chroma_paths: list[str]) -> int:
|
|
|
|
| 108 |
updated = 0
|
| 109 |
for path in chroma_paths:
|
| 110 |
try:
|
| 111 |
+
res = get_all(col, where={"path": path}, include=["metadatas"])
|
| 112 |
+
ids = res["ids"]
|
| 113 |
if not ids:
|
| 114 |
continue
|
| 115 |
metas = []
|
| 116 |
for old in res.get("metadatas") or []:
|
| 117 |
old = old or {}
|
| 118 |
+
nm = _base_metadata_user(user_id, old.get("path") or path, old.get("source_file") or "")
|
| 119 |
+
nm.update({k: old[k] for k in _CHUNK_KEYS if k in old})
|
|
|
|
|
|
|
|
|
|
| 120 |
metas.append(nm)
|
| 121 |
+
write_records(col, "update", ids, metadatas=metas)
|
| 122 |
updated += len(ids)
|
| 123 |
except Exception:
|
| 124 |
+
logger.warning("Metadata refresh failed for %s", path, exc_info=True)
|
| 125 |
continue
|
| 126 |
return updated
|
| 127 |
|
| 128 |
|
| 129 |
+
def ingest_text_for_path(user_id: str, rel_path: str, source_file: str, text: str, page_starts=None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
"""Ingest or replace chunks for a single extracted text path (e.g. after vision OCR)."""
|
| 131 |
if not text or not text.strip():
|
| 132 |
return {"chunks_created": 0, "message": "Empty text."}
|
| 133 |
collection = get_user_collection(user_id)
|
| 134 |
+
chunks, pages = _chunk_text_with_pages(text, page_starts)
|
| 135 |
+
_add_chunks_to_collection(collection, chunks, rel_path, source_file, user_id, pages)
|
|
|
|
| 136 |
return {"chunks_created": len(chunks), "message": f"Ingested {len(chunks)} chunks."}
|
| 137 |
|
| 138 |
|
| 139 |
def chunks_relocate_path(user_id: str, old_path: str, new_path: str, source_file: str | None = None) -> int:
|
| 140 |
"""Move all chunks from old_path to new_path (same text and embeddings, updated metadata)."""
|
| 141 |
col = get_user_collection(user_id)
|
| 142 |
+
res = get_all(col, where={"path": old_path}, include=["documents", "embeddings", "metadatas"])
|
| 143 |
docs = res.get("documents") or []
|
| 144 |
+
ids = res["ids"]
|
| 145 |
if not ids:
|
| 146 |
return 0
|
| 147 |
embs = res.get("embeddings")
|
|
|
|
| 148 |
if embs is None or len(embs) != len(docs):
|
| 149 |
+
embs = embed_texts(docs).tolist()
|
| 150 |
else:
|
| 151 |
+
embs = [list(e) for e in embs]
|
|
|
|
| 152 |
sf = source_file or os.path.basename(new_path.replace("\\", "/"))
|
| 153 |
+
base_meta = _base_metadata_user(user_id, new_path, sf)
|
| 154 |
old_metas = res.get("metadatas") or []
|
| 155 |
metadatas = []
|
| 156 |
for k in range(len(docs)):
|
| 157 |
+
m = dict(base_meta)
|
| 158 |
om = old_metas[k] if k < len(old_metas) else {}
|
| 159 |
+
if isinstance(om, dict) and om.get("page") is not None:
|
| 160 |
+
m["page"] = om["page"]
|
| 161 |
if isinstance(om, dict) and "chunk_index" in om:
|
| 162 |
try:
|
| 163 |
m["chunk_index"] = int(om["chunk_index"])
|
|
|
|
| 166 |
else:
|
| 167 |
m["chunk_index"] = k
|
| 168 |
metadatas.append(m)
|
| 169 |
+
# Add the new copies before deleting the old ones, so a failure never loses the chunks.
|
| 170 |
+
new_ids = chunk_ids_for_path(new_path, len(docs))
|
| 171 |
+
write_records(col, "upsert", new_ids, documents=list(docs), embeddings=embs, metadatas=metadatas)
|
| 172 |
+
keep = set(new_ids)
|
| 173 |
+
delete_ids(col, [i for i in ids if i not in keep])
|
| 174 |
return len(docs)
|
| 175 |
|
| 176 |
|
| 177 |
+
def chunks_relocate_files(user_id: str, file_paths: list[str], old_prefix: str, new_prefix: str) -> int:
|
| 178 |
+
"""Move the chunks of each file under old_prefix (paths taken from the folder tree) to new_prefix."""
|
| 179 |
old_prefix = old_prefix.replace("\\", "/").strip("/")
|
| 180 |
new_prefix = new_prefix.replace("\\", "/").strip("/")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
moved = 0
|
| 182 |
+
for p in file_paths:
|
| 183 |
+
if p == old_prefix or p.startswith(old_prefix + "/"):
|
| 184 |
+
moved += chunks_relocate_path(user_id, p, new_prefix + p[len(old_prefix) :])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
return moved
|
backend/legacy_migration.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
One-time move of note data saved under the old "hidden .txt twin" naming rule.
|
| 3 |
+
|
| 4 |
+
Older uploads stored the text of `notes.png` (search chunks + extracted text) and `notes.pdf`
|
| 5 |
+
(extracted text only) under a hidden `notes.txt` path. That clashed with a real `notes.txt`:
|
| 6 |
+
deleting or re-uploading one damaged the other. New uploads always use the real file path;
|
| 7 |
+
this moves old data to the real path once per user.
|
| 8 |
+
"""
|
| 9 |
+
import logging
|
| 10 |
+
import os
|
| 11 |
+
import threading
|
| 12 |
+
|
| 13 |
+
from backend.chroma_store import (
|
| 14 |
+
get_user_collection,
|
| 15 |
+
user_lock,
|
| 16 |
+
user_document_delete_by_path,
|
| 17 |
+
user_document_exists,
|
| 18 |
+
user_document_rename_path,
|
| 19 |
+
vfs_get_storage_version,
|
| 20 |
+
vfs_set_storage_version,
|
| 21 |
+
)
|
| 22 |
+
from backend.ingest_api import chunks_relocate_path
|
| 23 |
+
from backend.vfs_tree import flatten_file_paths
|
| 24 |
+
|
| 25 |
+
logger = logging.getLogger(__name__)
|
| 26 |
+
|
| 27 |
+
STORAGE_VERSION = 2 # 2 = text and chunks always stored under the real file path
|
| 28 |
+
_IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".gif", ".webp")
|
| 29 |
+
|
| 30 |
+
_checked_users: set[str] = set()
|
| 31 |
+
_checked_lock = threading.Lock()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _move_chunks(user_id: str, old_path: str, new_path: str) -> None:
|
| 35 |
+
col = get_user_collection(user_id)
|
| 36 |
+
old_ids = col.get(where={"path": old_path}, include=[]).get("ids") or []
|
| 37 |
+
if not old_ids:
|
| 38 |
+
return
|
| 39 |
+
if col.get(where={"path": new_path}, include=[], limit=1).get("ids"):
|
| 40 |
+
col.delete(ids=old_ids) # the real path already has its own data
|
| 41 |
+
return
|
| 42 |
+
chunks_relocate_path(user_id, old_path, new_path)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _move_document(user_id: str, old_path: str, new_path: str) -> None:
|
| 46 |
+
if not user_document_exists(user_id, old_path):
|
| 47 |
+
return
|
| 48 |
+
if user_document_exists(user_id, new_path):
|
| 49 |
+
user_document_delete_by_path(user_id, old_path)
|
| 50 |
+
else:
|
| 51 |
+
user_document_rename_path(user_id, old_path, new_path)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def migrate_legacy_twin_paths(user_id: str, tree: list) -> None:
|
| 55 |
+
"""Run the one-time move for this user if needed. Never raises (logs instead)."""
|
| 56 |
+
if user_id in _checked_users:
|
| 57 |
+
return
|
| 58 |
+
real_paths = set(flatten_file_paths(tree))
|
| 59 |
+
if not real_paths:
|
| 60 |
+
return # nothing stored yet; check again once the user has files
|
| 61 |
+
try:
|
| 62 |
+
with user_lock(user_id):
|
| 63 |
+
if vfs_get_storage_version(user_id) < STORAGE_VERSION:
|
| 64 |
+
# Images first: when notes.png and notes.pdf share one twin, the chunks belong to the image.
|
| 65 |
+
ordered = sorted(real_paths, key=lambda p: (not p.lower().endswith(_IMAGE_EXTS), p))
|
| 66 |
+
for path in ordered:
|
| 67 |
+
stem, ext = os.path.splitext(path)
|
| 68 |
+
ext = ext.lower()
|
| 69 |
+
if ext != ".pdf" and ext not in _IMAGE_EXTS:
|
| 70 |
+
continue
|
| 71 |
+
twin = stem + ".txt"
|
| 72 |
+
if twin in real_paths:
|
| 73 |
+
continue # a real .txt file owns that name; leave its data alone
|
| 74 |
+
if ext in _IMAGE_EXTS:
|
| 75 |
+
_move_chunks(user_id, twin, path)
|
| 76 |
+
_move_document(user_id, twin, path)
|
| 77 |
+
vfs_set_storage_version(user_id, STORAGE_VERSION)
|
| 78 |
+
except Exception:
|
| 79 |
+
logger.exception("Legacy storage migration failed for %s; will retry after restart", user_id)
|
| 80 |
+
with _checked_lock:
|
| 81 |
+
_checked_users.add(user_id)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def forget_user(user_id: str) -> None:
|
| 85 |
+
with _checked_lock:
|
| 86 |
+
_checked_users.discard(user_id)
|
backend/library.py
ADDED
|
@@ -0,0 +1,766 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
The shared course library: course PDFs read once on the server and searched by every student.
|
| 3 |
+
|
| 4 |
+
The PDFs come from a public Supabase Storage bucket (the Notes tab of SDE-Prep; see LIBRARY_* in
|
| 5 |
+
settings.py). They live in two shared collections, so nothing is copied per student:
|
| 6 |
+
|
| 7 |
+
- library_notes search passages + embeddings; metadata: path, subject, page and `y` (where on
|
| 8 |
+
the page the passage starts, 0 = top, 1 = bottom) so a viewer can scroll to it
|
| 9 |
+
- library_documents one record per PDF (eTag, status, page counts) plus its full text in parts,
|
| 10 |
+
which the study tools read
|
| 11 |
+
|
| 12 |
+
sync() brings the index in line with the bucket: new or changed PDFs (by eTag) are read and
|
| 13 |
+
indexed, removed ones are deleted. Pages that contain real text are read with PyMuPDF. Handwritten
|
| 14 |
+
pages (pen strokes) and scans are cut into page-shaped pieces at blank rows, so no line of writing
|
| 15 |
+
is split, and read with Sarvam Vision (at most 10 pieces per job, Sarvam's limit) or with Tesseract
|
| 16 |
+
when no Sarvam key is set. Students never start a sync: it runs from scripts/index_library.py, the
|
| 17 |
+
admin endpoint, or every LIBRARY_SYNC_HOURS.
|
| 18 |
+
"""
|
| 19 |
+
import bisect
|
| 20 |
+
import io
|
| 21 |
+
import logging
|
| 22 |
+
import threading
|
| 23 |
+
import time
|
| 24 |
+
from dataclasses import dataclass, field
|
| 25 |
+
from urllib.parse import quote
|
| 26 |
+
|
| 27 |
+
import httpx
|
| 28 |
+
import numpy as np
|
| 29 |
+
from fastapi import HTTPException
|
| 30 |
+
|
| 31 |
+
from backend import llm_pipeline, settings, usage
|
| 32 |
+
from backend.chroma_store import (
|
| 33 |
+
_get_collection_or_none,
|
| 34 |
+
_get_or_create_collection,
|
| 35 |
+
_read_parts,
|
| 36 |
+
_write_parts,
|
| 37 |
+
collection_distance_space,
|
| 38 |
+
delete_ids,
|
| 39 |
+
distance_to_similarity,
|
| 40 |
+
get_all,
|
| 41 |
+
short_id,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
logger = logging.getLogger(__name__)
|
| 45 |
+
|
| 46 |
+
NOTES_COLLECTION = "library_notes"
|
| 47 |
+
DOCS_COLLECTION = "library_documents"
|
| 48 |
+
USAGE_ID = "library" # usage counters for pages the library sent to Sarvam (cost on the admin page)
|
| 49 |
+
OCR_BATCH = 10 # Sarvam Vision reads at most 10 pages per job
|
| 50 |
+
MIN_FILE_BYTES = 1000 # smaller "PDFs" in the bucket are empty placeholders
|
| 51 |
+
MAX_FILE_BYTES = 200 * 1024 * 1024
|
| 52 |
+
TILE_RATIO = 1.35 # height / width of one piece sent to OCR: about a portrait page
|
| 53 |
+
OCR_WIDTH_PX = 1600 # render width for OCR: handwriting stays legible, images stay small
|
| 54 |
+
STATUS_CACHE_SECONDS = 60
|
| 55 |
+
NOT_READY = "These course notes aren't ready for AI yet. Please try again later."
|
| 56 |
+
|
| 57 |
+
FOLDER_NAMES = {
|
| 58 |
+
"class-notes": "Class Notes",
|
| 59 |
+
"tutorials-assignments": "Tutorials/Assignments",
|
| 60 |
+
"exam-practice": "Exam Practice",
|
| 61 |
+
"past-papers": "Past Papers",
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class BudgetReached(Exception):
|
| 66 |
+
"""This month's AI budget is used up; files that need Sarvam wait for the next sync."""
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# ---------- Paths ----------
|
| 70 |
+
def _clean(path: str) -> str:
|
| 71 |
+
p = (path or "").replace("\\", "/").strip().strip("/")
|
| 72 |
+
return "" if ".." in p.split("/") else p
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _allowed(path: str) -> bool:
|
| 76 |
+
return any(path == pre or path.startswith(pre + "/") for pre in settings.LIBRARY_PREFIXES)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def subject_of(path: str) -> str:
|
| 80 |
+
"""'category/subject' of a library path, e.g. plaksha-university/discrete-maths."""
|
| 81 |
+
parts = _clean(path).split("/")
|
| 82 |
+
return "/".join(parts[:2]) if len(parts) >= 2 else ""
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def scope_of(library_path: str) -> tuple[str, str]:
|
| 86 |
+
"""
|
| 87 |
+
(PDF path or "", subject) for what a client sends: the storage path of the PDF that is open,
|
| 88 |
+
or just a subject prefix. ("", "") when the path is outside the library.
|
| 89 |
+
"""
|
| 90 |
+
p = _clean(library_path)
|
| 91 |
+
if not p or not _allowed(p):
|
| 92 |
+
return "", ""
|
| 93 |
+
return (p if p.lower().endswith(".pdf") else ""), subject_of(p)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _title(slug: str) -> str:
|
| 97 |
+
return slug.replace("-", " ").replace("_", " ").strip().title()
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def subject_label(subject: str) -> str:
|
| 101 |
+
parts = subject.split("/")
|
| 102 |
+
return _title(parts[1]) if len(parts) > 1 else _title(subject)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def label_of(path: str) -> str:
|
| 106 |
+
"""Readable name for answers, e.g. 'Discrete Maths › Class Notes › L1'."""
|
| 107 |
+
parts = _clean(path).split("/")
|
| 108 |
+
subject = _title(parts[1]) if len(parts) > 2 else ""
|
| 109 |
+
folder = FOLDER_NAMES.get(parts[2], _title(parts[2])) if len(parts) > 3 else ""
|
| 110 |
+
name = parts[-1].rsplit(".", 1)[0] if parts else ""
|
| 111 |
+
return " › ".join(x for x in (subject, folder, name) if x)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _doc_id(path: str) -> str:
|
| 115 |
+
return short_id("libdoc", path)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _chunk_id_base(path: str) -> str:
|
| 119 |
+
return short_id("lib", path)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# ---------- Collections ----------
|
| 123 |
+
def _notes(create: bool):
|
| 124 |
+
return _get_or_create_collection(NOTES_COLLECTION) if create else _get_collection_or_none(NOTES_COLLECTION)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _docs(create: bool):
|
| 128 |
+
return _get_or_create_collection(DOCS_COLLECTION) if create else _get_collection_or_none(DOCS_COLLECTION)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def indexed_files() -> dict[str, dict]:
|
| 132 |
+
"""{path: details} for every PDF the library knows about (any status)."""
|
| 133 |
+
col = _docs(create=False)
|
| 134 |
+
if col is None:
|
| 135 |
+
return {}
|
| 136 |
+
res = get_all(col, where={"kind": "library_file"}, include=["metadatas"])
|
| 137 |
+
return {m["path"]: m for m in res.get("metadatas") or [] if m and m.get("path")}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def document_text(path: str) -> str:
|
| 141 |
+
"""Full text read from a library PDF ("" if it isn't indexed)."""
|
| 142 |
+
col = _docs(create=False)
|
| 143 |
+
if col is None:
|
| 144 |
+
return ""
|
| 145 |
+
try:
|
| 146 |
+
return (_read_parts(col, _doc_id(path)) or "").strip()
|
| 147 |
+
except Exception:
|
| 148 |
+
logger.warning("Could not read library text for %s", path, exc_info=True)
|
| 149 |
+
return ""
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
# ---------- The bucket ----------
|
| 153 |
+
def _storage_headers() -> dict:
|
| 154 |
+
key = settings.LIBRARY_SUPABASE_KEY
|
| 155 |
+
return {"apikey": key, "Authorization": f"Bearer {key}"}
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def list_source_files() -> list[dict]:
|
| 159 |
+
"""Every PDF under LIBRARY_PREFIXES in the bucket: [{path, etag, size}], placeholders left out."""
|
| 160 |
+
url = f"{settings.LIBRARY_SUPABASE_URL}/storage/v1/object/list/{settings.LIBRARY_BUCKET}"
|
| 161 |
+
out: list[dict] = []
|
| 162 |
+
|
| 163 |
+
def walk(prefix: str) -> None:
|
| 164 |
+
offset = 0
|
| 165 |
+
while True:
|
| 166 |
+
r = httpx.post(
|
| 167 |
+
url,
|
| 168 |
+
headers=_storage_headers(),
|
| 169 |
+
json={"prefix": prefix, "limit": 100, "offset": offset, "sortBy": {"column": "name", "order": "asc"}},
|
| 170 |
+
timeout=30,
|
| 171 |
+
)
|
| 172 |
+
r.raise_for_status()
|
| 173 |
+
items = r.json() or []
|
| 174 |
+
for it in items:
|
| 175 |
+
name = it.get("name") or ""
|
| 176 |
+
if not name or name.startswith(".emptyFolderPlaceholder"):
|
| 177 |
+
continue
|
| 178 |
+
path = f"{prefix}/{name}"
|
| 179 |
+
if it.get("id") is None: # a folder
|
| 180 |
+
walk(path)
|
| 181 |
+
continue
|
| 182 |
+
meta = it.get("metadata") or {}
|
| 183 |
+
size = int(meta.get("size") or 0)
|
| 184 |
+
if name.lower().endswith(".pdf") and MIN_FILE_BYTES <= size <= MAX_FILE_BYTES:
|
| 185 |
+
etag = str(meta.get("eTag") or it.get("updated_at") or "").strip('"')
|
| 186 |
+
out.append({"path": path, "etag": etag, "size": size})
|
| 187 |
+
if len(items) < 100:
|
| 188 |
+
return
|
| 189 |
+
offset += 100
|
| 190 |
+
|
| 191 |
+
for prefix in settings.LIBRARY_PREFIXES:
|
| 192 |
+
walk(prefix)
|
| 193 |
+
return out
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def download(path: str) -> bytes:
|
| 197 |
+
url = (
|
| 198 |
+
f"{settings.LIBRARY_SUPABASE_URL}/storage/v1/object/public/{settings.LIBRARY_BUCKET}/"
|
| 199 |
+
+ "/".join(quote(seg) for seg in path.split("/"))
|
| 200 |
+
)
|
| 201 |
+
r = httpx.get(url, timeout=300, follow_redirects=True)
|
| 202 |
+
r.raise_for_status()
|
| 203 |
+
return r.content
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# ---------- Reading a PDF ----------
|
| 207 |
+
@dataclass
|
| 208 |
+
class Tile:
|
| 209 |
+
"""A page-shaped piece of a page, rendered for OCR."""
|
| 210 |
+
page: int # 1-based page number
|
| 211 |
+
y0: float # where the piece starts on the page (0..1)
|
| 212 |
+
image: bytes # PNG
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
@dataclass
|
| 216 |
+
class PdfText:
|
| 217 |
+
text: str = ""
|
| 218 |
+
anchors: list[tuple[int, int, float]] = field(default_factory=list) # (offset in text, page, y)
|
| 219 |
+
pages: int = 0
|
| 220 |
+
ocr_pieces: int = 0 # pieces that needed OCR
|
| 221 |
+
sarvam_pieces: int = 0 # pieces Sarvam read (paid)
|
| 222 |
+
method: str = "" # text | ocr | mixed
|
| 223 |
+
notes: list[str] = field(default_factory=list)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def _ocr_mode() -> str:
|
| 227 |
+
mode = settings.LIBRARY_OCR
|
| 228 |
+
if mode == "auto":
|
| 229 |
+
return "sarvam" if llm_pipeline._sarvam_api_key() else "tesseract"
|
| 230 |
+
return mode if mode in ("sarvam", "tesseract", "off") else "tesseract"
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def _needs_ocr(page, text: str) -> bool:
|
| 234 |
+
"""Handwriting (many pen strokes) or a scan (a large image) needs OCR; typed pages are read as text."""
|
| 235 |
+
chars = len(text)
|
| 236 |
+
strokes = len(page.get_drawings())
|
| 237 |
+
if strokes >= 150:
|
| 238 |
+
return True # mostly handwriting (OneNote ink exports have hundreds of strokes per page)
|
| 239 |
+
if chars >= 300:
|
| 240 |
+
return False # real text with a few diagrams
|
| 241 |
+
area = max(page.rect.width * page.rect.height, 1.0)
|
| 242 |
+
for info in page.get_image_info():
|
| 243 |
+
x0, y0, x1, y1 = info.get("bbox") or (0, 0, 0, 0)
|
| 244 |
+
if (x1 - x0) * (y1 - y0) >= 0.3 * area:
|
| 245 |
+
return True # a scanned page or a photo of one
|
| 246 |
+
return strokes >= 20
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def _tile_count(page) -> int:
|
| 250 |
+
w, h = page.rect.width, page.rect.height
|
| 251 |
+
return 1 if h <= w * 1.6 else max(2, round(h / (w * TILE_RATIO)))
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _cut_rows(page, n: int) -> list[float]:
|
| 255 |
+
"""n-1 cut positions (points), each moved to the emptiest row near an even split."""
|
| 256 |
+
import fitz # PyMuPDF
|
| 257 |
+
|
| 258 |
+
w, h = page.rect.width, page.rect.height
|
| 259 |
+
scale = min(1.0, 400 / max(w, 1.0))
|
| 260 |
+
pix = page.get_pixmap(matrix=fitz.Matrix(scale, scale), colorspace=fitz.csGRAY, alpha=False)
|
| 261 |
+
gray = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.height, pix.stride)[:, : pix.width]
|
| 262 |
+
ink = (gray < 200).sum(axis=1) # dark pixels per row: writing, not the light page background
|
| 263 |
+
step = h / n
|
| 264 |
+
cuts: list[float] = []
|
| 265 |
+
for k in range(1, n):
|
| 266 |
+
target = k * step
|
| 267 |
+
lo = max(int((target - 0.15 * step) * scale), 0)
|
| 268 |
+
hi = min(int((target + 0.15 * step) * scale), len(ink) - 1)
|
| 269 |
+
if hi <= lo:
|
| 270 |
+
cuts.append(target)
|
| 271 |
+
continue
|
| 272 |
+
window = ink[lo : hi + 1]
|
| 273 |
+
candidates = np.flatnonzero(window == window.min()) + lo
|
| 274 |
+
best = int(candidates[np.argmin(np.abs(candidates - target * scale))])
|
| 275 |
+
cuts.append(best / scale)
|
| 276 |
+
return cuts
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def _tiles(page) -> list[Tile]:
|
| 280 |
+
import fitz # PyMuPDF
|
| 281 |
+
|
| 282 |
+
w, h = page.rect.width, page.rect.height
|
| 283 |
+
n = _tile_count(page)
|
| 284 |
+
ys = [0.0, *(_cut_rows(page, n) if n > 1 else []), h]
|
| 285 |
+
zoom = min(OCR_WIDTH_PX / max(w, 1.0), 3.0)
|
| 286 |
+
tiles = []
|
| 287 |
+
for y0, y1 in zip(ys, ys[1:]):
|
| 288 |
+
if y1 - y0 < 8:
|
| 289 |
+
continue
|
| 290 |
+
pix = page.get_pixmap(matrix=fitz.Matrix(zoom, zoom), clip=fitz.Rect(0, y0, w, y1), alpha=False)
|
| 291 |
+
tiles.append(Tile(page=page.number + 1, y0=y0 / h, image=pix.tobytes("png")))
|
| 292 |
+
return tiles
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def _tesseract(tile: Tile) -> str:
|
| 296 |
+
import pytesseract
|
| 297 |
+
from PIL import Image
|
| 298 |
+
|
| 299 |
+
return pytesseract.image_to_string(Image.open(io.BytesIO(tile.image))).strip()
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def _split_by_pages(text: str, page_texts: list[str], n: int) -> list[str]:
|
| 303 |
+
"""Split one OCR job's text back into its n pieces (all of it to the first when that fails)."""
|
| 304 |
+
from backend.pages import anchor_page_starts
|
| 305 |
+
|
| 306 |
+
out = [""] * n
|
| 307 |
+
starts = anchor_page_starts(text, page_texts) if n > 1 else None
|
| 308 |
+
if not starts:
|
| 309 |
+
out[0] = text
|
| 310 |
+
return out
|
| 311 |
+
bounds = [*starts, (len(text), 0)]
|
| 312 |
+
for (start, number), (end, _) in zip(bounds, bounds[1:]):
|
| 313 |
+
i = min(max(number, 1), n) - 1
|
| 314 |
+
out[i] = (out[i] + "\n\n" + text[start:end]).strip()
|
| 315 |
+
return out
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def _sarvam_batch(tiles: list[Tile]) -> list[str] | None:
|
| 319 |
+
"""Text of each piece from one Sarvam Vision job (≤ 10 pieces), or None if the job failed."""
|
| 320 |
+
import fitz # PyMuPDF
|
| 321 |
+
|
| 322 |
+
doc = fitz.open()
|
| 323 |
+
try:
|
| 324 |
+
for t in tiles:
|
| 325 |
+
with fitz.open(stream=t.image, filetype="png") as img:
|
| 326 |
+
rect = img[0].rect
|
| 327 |
+
page = doc.new_page(width=rect.width, height=rect.height)
|
| 328 |
+
page.insert_image(page.rect, stream=t.image)
|
| 329 |
+
pdf = doc.tobytes()
|
| 330 |
+
finally:
|
| 331 |
+
doc.close()
|
| 332 |
+
text, err, page_texts = llm_pipeline.transcribe_pdf_with_pages(pdf)
|
| 333 |
+
if err or not (text or "").strip():
|
| 334 |
+
logger.warning("Sarvam Vision failed for a library batch: %s", err or "empty output")
|
| 335 |
+
return None
|
| 336 |
+
return _split_by_pages(text.strip(), page_texts, len(tiles))
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def _check_budget() -> None:
|
| 340 |
+
try:
|
| 341 |
+
usage.check_budget()
|
| 342 |
+
except HTTPException as e:
|
| 343 |
+
raise BudgetReached(str(e.detail)) from e
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def _ocr(tiles: list[Tile], mode: str, result: PdfText) -> list[str]:
|
| 347 |
+
if mode != "sarvam":
|
| 348 |
+
return [_tesseract(t) for t in tiles]
|
| 349 |
+
texts: list[str] = []
|
| 350 |
+
for i in range(0, len(tiles), OCR_BATCH):
|
| 351 |
+
batch = tiles[i : i + OCR_BATCH]
|
| 352 |
+
_check_budget()
|
| 353 |
+
got = _sarvam_batch(batch)
|
| 354 |
+
if got is None:
|
| 355 |
+
result.notes.append("sarvam_failed_used_tesseract")
|
| 356 |
+
got = [_tesseract(t) for t in batch]
|
| 357 |
+
else:
|
| 358 |
+
result.sarvam_pieces += len(batch)
|
| 359 |
+
texts.extend(got)
|
| 360 |
+
return texts
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def read_pdf(data: bytes, ocr: str = "tesseract", estimate_only: bool = False) -> PdfText:
|
| 364 |
+
"""
|
| 365 |
+
The text of a PDF in reading order, with an anchor (offset, page, y) wherever a piece starts.
|
| 366 |
+
estimate_only counts the pieces that would need OCR without reading them (for --dry-run).
|
| 367 |
+
"""
|
| 368 |
+
import fitz # PyMuPDF
|
| 369 |
+
|
| 370 |
+
result = PdfText()
|
| 371 |
+
pieces: list[tuple[int, float, str]] = [] # (page, y, text)
|
| 372 |
+
ocr_pages: dict[int, str] = {} # page → PyMuPDF's text for it, used only if OCR reads nothing
|
| 373 |
+
pending: list[Tile] = []
|
| 374 |
+
|
| 375 |
+
def read_pending(everything: bool) -> None:
|
| 376 |
+
# Full jobs of OCR_BATCH pieces across pages; the rest waits for the next page.
|
| 377 |
+
n = len(pending) if everything else len(pending) // OCR_BATCH * OCR_BATCH
|
| 378 |
+
batch = pending[:n]
|
| 379 |
+
del pending[:n]
|
| 380 |
+
for t, s in zip(batch, _ocr(batch, ocr, result) if batch else []):
|
| 381 |
+
if (s or "").strip():
|
| 382 |
+
pieces.append((t.page, t.y0, s.strip()))
|
| 383 |
+
|
| 384 |
+
with fitz.open(stream=data, filetype="pdf") as doc:
|
| 385 |
+
result.pages = len(doc)
|
| 386 |
+
for page in doc:
|
| 387 |
+
text = (page.get_text() or "").strip()
|
| 388 |
+
if ocr == "off" or not _needs_ocr(page, text):
|
| 389 |
+
if text:
|
| 390 |
+
pieces.append((page.number + 1, 0.0, text))
|
| 391 |
+
continue
|
| 392 |
+
ocr_pages[page.number + 1] = text
|
| 393 |
+
result.ocr_pieces += _tile_count(page)
|
| 394 |
+
if estimate_only:
|
| 395 |
+
continue
|
| 396 |
+
pending.extend(_tiles(page))
|
| 397 |
+
read_pending(everything=False)
|
| 398 |
+
if not estimate_only:
|
| 399 |
+
read_pending(everything=True)
|
| 400 |
+
if estimate_only:
|
| 401 |
+
return result
|
| 402 |
+
# OCR also reads the typed bits (e.g. a OneNote title); PyMuPDF's text is only a fallback.
|
| 403 |
+
read_pages = {p for p, _, _ in pieces}
|
| 404 |
+
pieces.extend((p, 0.0, t) for p, t in ocr_pages.items() if t and p not in read_pages)
|
| 405 |
+
pieces.sort(key=lambda p: (p[0], p[1]))
|
| 406 |
+
parts: list[str] = []
|
| 407 |
+
offset = 0
|
| 408 |
+
for number, y, text in pieces:
|
| 409 |
+
if parts:
|
| 410 |
+
parts.append("\n\n")
|
| 411 |
+
offset += 2
|
| 412 |
+
result.anchors.append((offset, number, y))
|
| 413 |
+
parts.append(text)
|
| 414 |
+
offset += len(text)
|
| 415 |
+
result.text = "".join(parts)
|
| 416 |
+
result.method = "text" if not ocr_pages else ("ocr" if len(ocr_pages) == result.pages else "mixed")
|
| 417 |
+
return result
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
# ---------- Storing ----------
|
| 421 |
+
def _chunks_with_positions(text: str, anchors: list[tuple[int, int, float]]) -> list[tuple[str, int | None, float | None]]:
|
| 422 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 423 |
+
|
| 424 |
+
from backend.ingest_api import CHUNK_OVERLAP, CHUNK_SIZE
|
| 425 |
+
|
| 426 |
+
splitter = RecursiveCharacterTextSplitter(chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP, add_start_index=True)
|
| 427 |
+
offsets = [a[0] for a in anchors]
|
| 428 |
+
out = []
|
| 429 |
+
for d in splitter.create_documents([text]):
|
| 430 |
+
if not anchors:
|
| 431 |
+
out.append((d.page_content, None, None))
|
| 432 |
+
continue
|
| 433 |
+
start = max(int(d.metadata.get("start_index") or 0), 0)
|
| 434 |
+
_, page, y = anchors[max(bisect.bisect_right(offsets, start) - 1, 0)]
|
| 435 |
+
out.append((d.page_content, page, y))
|
| 436 |
+
return out
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def _file_meta(entry: dict, status: str, **extra) -> dict:
|
| 440 |
+
path = entry["path"]
|
| 441 |
+
return {
|
| 442 |
+
"path": path,
|
| 443 |
+
"subject": subject_of(path),
|
| 444 |
+
"etag": entry.get("etag") or "",
|
| 445 |
+
"size": int(entry.get("size") or 0),
|
| 446 |
+
"status": status,
|
| 447 |
+
"updated_at": int(time.time()),
|
| 448 |
+
**extra,
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def _store(entry: dict, pdf: PdfText) -> int:
|
| 453 |
+
"""Replace the passages and stored text of one PDF. Returns the number of passages."""
|
| 454 |
+
from backend.ingest_api import embed_texts
|
| 455 |
+
|
| 456 |
+
path = entry["path"]
|
| 457 |
+
col = _notes(create=True)
|
| 458 |
+
old_ids = get_all(col, where={"path": path}, include=[])["ids"]
|
| 459 |
+
chunks = _chunks_with_positions(pdf.text, pdf.anchors)
|
| 460 |
+
base = {
|
| 461 |
+
"path": path,
|
| 462 |
+
"subject": subject_of(path),
|
| 463 |
+
"source_file": path.rsplit("/", 1)[-1],
|
| 464 |
+
"label": label_of(path),
|
| 465 |
+
"pages": int(pdf.pages),
|
| 466 |
+
"library": 1,
|
| 467 |
+
}
|
| 468 |
+
new_ids: list[str] = []
|
| 469 |
+
for i in range(0, len(chunks), 50):
|
| 470 |
+
batch = chunks[i : i + 50]
|
| 471 |
+
ids = [f"{_chunk_id_base(path)}_{i + j}" for j in range(len(batch))]
|
| 472 |
+
metas = []
|
| 473 |
+
for j, (_, page, y) in enumerate(batch):
|
| 474 |
+
m = {**base, "chunk_index": i + j}
|
| 475 |
+
if page is not None:
|
| 476 |
+
m["page"] = int(page)
|
| 477 |
+
if y is not None:
|
| 478 |
+
m["y"] = round(float(y), 4)
|
| 479 |
+
metas.append(m)
|
| 480 |
+
col.upsert(
|
| 481 |
+
ids=ids,
|
| 482 |
+
documents=[c[0] for c in batch],
|
| 483 |
+
embeddings=embed_texts([c[0] for c in batch]).tolist(),
|
| 484 |
+
metadatas=metas,
|
| 485 |
+
)
|
| 486 |
+
new_ids.extend(ids)
|
| 487 |
+
keep = set(new_ids)
|
| 488 |
+
delete_ids(col, [x for x in old_ids if x not in keep])
|
| 489 |
+
_write_parts(
|
| 490 |
+
_docs(create=True),
|
| 491 |
+
_doc_id(path),
|
| 492 |
+
pdf.text,
|
| 493 |
+
"library_file",
|
| 494 |
+
_file_meta(
|
| 495 |
+
entry,
|
| 496 |
+
"ok",
|
| 497 |
+
pages=pdf.pages,
|
| 498 |
+
ocr_pieces=pdf.ocr_pieces,
|
| 499 |
+
sarvam_pieces=pdf.sarvam_pieces,
|
| 500 |
+
chunks=len(chunks),
|
| 501 |
+
chars=len(pdf.text),
|
| 502 |
+
method=pdf.method,
|
| 503 |
+
note=",".join(sorted(set(pdf.notes))),
|
| 504 |
+
),
|
| 505 |
+
)
|
| 506 |
+
return len(chunks)
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def _store_status(entry: dict, status: str, error: str = "") -> None:
|
| 510 |
+
"""Record a PDF that couldn't be indexed (yet), keeping any passages from an earlier version."""
|
| 511 |
+
_write_parts(_docs(create=True), _doc_id(entry["path"]), "", "library_file", _file_meta(entry, status, error=error[:300]))
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def remove(path: str) -> None:
|
| 515 |
+
col = _notes(create=False)
|
| 516 |
+
if col is not None:
|
| 517 |
+
delete_ids(col, get_all(col, where={"path": path}, include=[])["ids"])
|
| 518 |
+
docs = _docs(create=False)
|
| 519 |
+
if docs is None:
|
| 520 |
+
return
|
| 521 |
+
doc_id = _doc_id(path)
|
| 522 |
+
res = docs.get(ids=[doc_id], include=["metadatas"])
|
| 523 |
+
if res.get("ids"):
|
| 524 |
+
meta = (res.get("metadatas") or [{}])[0] or {}
|
| 525 |
+
parts, version = int(meta.get("parts") or 0), str(meta.get("version") or "")
|
| 526 |
+
delete_ids(docs, [f"{doc_id}#{version}#{k}" for k in range(parts)] + [doc_id])
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
# ---------- Sync ----------
|
| 530 |
+
_sync_lock = threading.Lock()
|
| 531 |
+
_state: dict = {"running": False, "current": None, "started_at": None, "finished_at": None, "last": None}
|
| 532 |
+
_status_cache: dict = {"at": 0.0, "value": None}
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def sync_state() -> dict:
|
| 536 |
+
return dict(_state)
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def sync(
|
| 540 |
+
dry_run: bool = False,
|
| 541 |
+
only: list[str] | None = None,
|
| 542 |
+
limit: int | None = None,
|
| 543 |
+
force: bool = False,
|
| 544 |
+
log=logger.info,
|
| 545 |
+
) -> dict:
|
| 546 |
+
"""
|
| 547 |
+
Index new or changed PDFs and drop removed ones. `only` keeps paths starting with any of the
|
| 548 |
+
given prefixes (and then nothing outside them is removed); `limit` caps how many files are read.
|
| 549 |
+
Raises RuntimeError if another sync is already running.
|
| 550 |
+
"""
|
| 551 |
+
if not _sync_lock.acquire(blocking=False):
|
| 552 |
+
raise RuntimeError("A library sync is already running.")
|
| 553 |
+
try:
|
| 554 |
+
_state.update(running=True, current=None, started_at=time.time())
|
| 555 |
+
mode = _ocr_mode()
|
| 556 |
+
source = list_source_files()
|
| 557 |
+
prefixes = [_clean(o) for o in (only or []) if _clean(o)]
|
| 558 |
+
if prefixes:
|
| 559 |
+
source = [e for e in source if any(e["path"] == o or e["path"].startswith(o) for o in prefixes)]
|
| 560 |
+
known = indexed_files()
|
| 561 |
+
source_paths = {e["path"] for e in source}
|
| 562 |
+
|
| 563 |
+
def stale(e: dict) -> bool:
|
| 564 |
+
# "empty" PDFs (nothing readable) are only re-read when they change: OCR costs money.
|
| 565 |
+
k = known.get(e["path"])
|
| 566 |
+
return force or not k or k.get("etag") != e["etag"] or k.get("status") in ("failed", "pending")
|
| 567 |
+
|
| 568 |
+
todo = [e for e in source if stale(e)]
|
| 569 |
+
if limit:
|
| 570 |
+
todo = todo[: max(int(limit), 0)]
|
| 571 |
+
gone = [] if prefixes else [p for p in known if p not in source_paths]
|
| 572 |
+
summary = {
|
| 573 |
+
"dry_run": dry_run,
|
| 574 |
+
"ocr": mode,
|
| 575 |
+
"source_files": len(source),
|
| 576 |
+
"up_to_date": len(source) - len([e for e in source if stale(e)]),
|
| 577 |
+
"to_index": len(todo),
|
| 578 |
+
"indexed": 0,
|
| 579 |
+
"empty": 0,
|
| 580 |
+
"failed": 0,
|
| 581 |
+
"waiting_for_budget": 0,
|
| 582 |
+
"removed": 0,
|
| 583 |
+
"pages": 0,
|
| 584 |
+
"ocr_pieces": 0,
|
| 585 |
+
"sarvam_pieces": 0,
|
| 586 |
+
}
|
| 587 |
+
budget_hit = False
|
| 588 |
+
for n, entry in enumerate(todo, 1):
|
| 589 |
+
path = entry["path"]
|
| 590 |
+
_state["current"] = path
|
| 591 |
+
try:
|
| 592 |
+
data = download(path)
|
| 593 |
+
if budget_hit and mode == "sarvam" and not dry_run:
|
| 594 |
+
pdf = read_pdf(data, ocr=mode, estimate_only=True)
|
| 595 |
+
if pdf.ocr_pieces:
|
| 596 |
+
raise BudgetReached("monthly AI budget reached")
|
| 597 |
+
pdf = read_pdf(data, ocr=mode, estimate_only=dry_run)
|
| 598 |
+
except BudgetReached as e:
|
| 599 |
+
budget_hit = True
|
| 600 |
+
summary["waiting_for_budget"] += 1
|
| 601 |
+
if not dry_run and path not in known:
|
| 602 |
+
_store_status(entry, "pending", str(e))
|
| 603 |
+
log(f"[{n}/{len(todo)}] {path}: waiting for next month's AI budget")
|
| 604 |
+
continue
|
| 605 |
+
except Exception as e:
|
| 606 |
+
logger.exception("Library: could not read %s", path)
|
| 607 |
+
summary["failed"] += 1
|
| 608 |
+
# A PDF that was indexed before keeps its earlier passages and text.
|
| 609 |
+
if not dry_run and known.get(path, {}).get("status") != "ok":
|
| 610 |
+
_store_status(entry, "failed", f"{type(e).__name__}: {e}")
|
| 611 |
+
log(f"[{n}/{len(todo)}] {path}: failed ({type(e).__name__}: {e})")
|
| 612 |
+
continue
|
| 613 |
+
summary["pages"] += pdf.pages
|
| 614 |
+
summary["ocr_pieces"] += pdf.ocr_pieces
|
| 615 |
+
if dry_run:
|
| 616 |
+
log(f"[{n}/{len(todo)}] {path}: {pdf.pages} page(s), {pdf.ocr_pieces} piece(s) to OCR")
|
| 617 |
+
continue
|
| 618 |
+
if pdf.sarvam_pieces:
|
| 619 |
+
summary["sarvam_pieces"] += pdf.sarvam_pieces
|
| 620 |
+
usage.record(USAGE_ID, pages_read=pdf.sarvam_pieces)
|
| 621 |
+
if not pdf.text.strip():
|
| 622 |
+
summary["empty"] += 1
|
| 623 |
+
_store_status(entry, "empty", "No text could be read from this PDF.")
|
| 624 |
+
log(f"[{n}/{len(todo)}] {path}: no text found")
|
| 625 |
+
continue
|
| 626 |
+
chunks = _store(entry, pdf)
|
| 627 |
+
summary["indexed"] += 1
|
| 628 |
+
log(f"[{n}/{len(todo)}] {path}: {chunks} passages ({pdf.method}, {pdf.ocr_pieces} OCR pieces)")
|
| 629 |
+
if not dry_run:
|
| 630 |
+
for p in gone:
|
| 631 |
+
remove(p)
|
| 632 |
+
log(f"removed {p}")
|
| 633 |
+
summary["removed"] = len(gone)
|
| 634 |
+
else:
|
| 635 |
+
summary["would_remove"] = len(gone)
|
| 636 |
+
_state["last"] = summary
|
| 637 |
+
_status_cache["at"] = 0.0
|
| 638 |
+
return summary
|
| 639 |
+
finally:
|
| 640 |
+
_state.update(running=False, current=None, finished_at=time.time())
|
| 641 |
+
_sync_lock.release()
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
def _sync_quietly(**kwargs) -> None:
|
| 645 |
+
try:
|
| 646 |
+
summary = sync(**kwargs)
|
| 647 |
+
logger.info("Library sync finished: %s", summary)
|
| 648 |
+
except RuntimeError as e:
|
| 649 |
+
logger.info("%s", e)
|
| 650 |
+
except Exception as e:
|
| 651 |
+
logger.exception("Library sync failed")
|
| 652 |
+
from backend import alerts
|
| 653 |
+
|
| 654 |
+
alerts.notify("library-sync", f"Library sync failed: {type(e).__name__}: {e}")
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
def sync_in_background(force: bool = False) -> bool:
|
| 658 |
+
"""Start a sync in a background thread. False if one is already running."""
|
| 659 |
+
if _state["running"]:
|
| 660 |
+
return False
|
| 661 |
+
threading.Thread(target=_sync_quietly, kwargs={"force": force}, name="library-sync", daemon=True).start()
|
| 662 |
+
return True
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
_started = False
|
| 666 |
+
_start_lock = threading.Lock()
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
def start() -> None:
|
| 670 |
+
"""Re-check the bucket every LIBRARY_SYNC_HOURS (off unless set: reading pages with Sarvam costs money)."""
|
| 671 |
+
global _started
|
| 672 |
+
with _start_lock:
|
| 673 |
+
if _started or not settings.LIBRARY_ENABLED or settings.LIBRARY_SYNC_HOURS <= 0:
|
| 674 |
+
return
|
| 675 |
+
_started = True
|
| 676 |
+
|
| 677 |
+
def loop() -> None:
|
| 678 |
+
while True:
|
| 679 |
+
_sync_quietly()
|
| 680 |
+
time.sleep(max(settings.LIBRARY_SYNC_HOURS, 0.25) * 3600)
|
| 681 |
+
|
| 682 |
+
threading.Thread(target=loop, name="library-sync-loop", daemon=True).start()
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
def public_status() -> dict:
|
| 686 |
+
"""What the client needs to know: which PDFs can be asked about (cached for a minute)."""
|
| 687 |
+
if not settings.LIBRARY_ENABLED:
|
| 688 |
+
return {"enabled": False, "ready": [], "syncing": False}
|
| 689 |
+
now = time.time()
|
| 690 |
+
if _status_cache["value"] is None or now - _status_cache["at"] > STATUS_CACHE_SECONDS:
|
| 691 |
+
files = indexed_files()
|
| 692 |
+
_status_cache["value"] = sorted(p for p, m in files.items() if m.get("status") == "ok")
|
| 693 |
+
_status_cache["at"] = now
|
| 694 |
+
return {"enabled": True, "ready": list(_status_cache["value"]), "syncing": bool(_state["running"])}
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
# ---------- Search + study context ----------
|
| 698 |
+
def search(q_emb: list[float], where: dict, n_results: int) -> list[dict]:
|
| 699 |
+
"""Best library passages matching `where`, scored as cosine similarity (same scale as notes)."""
|
| 700 |
+
if not settings.LIBRARY_ENABLED:
|
| 701 |
+
return []
|
| 702 |
+
col = _notes(create=False)
|
| 703 |
+
if col is None:
|
| 704 |
+
return []
|
| 705 |
+
try:
|
| 706 |
+
res = col.query(
|
| 707 |
+
query_embeddings=[q_emb],
|
| 708 |
+
n_results=n_results,
|
| 709 |
+
include=["documents", "metadatas", "distances"],
|
| 710 |
+
where=where,
|
| 711 |
+
)
|
| 712 |
+
except Exception:
|
| 713 |
+
logger.warning("Library search failed", exc_info=True)
|
| 714 |
+
return []
|
| 715 |
+
space = collection_distance_space(col)
|
| 716 |
+
ids = (res.get("ids") or [[]])[0] or []
|
| 717 |
+
docs = (res.get("documents") or [[]])[0] or []
|
| 718 |
+
metas = (res.get("metadatas") or [[]])[0] or []
|
| 719 |
+
dists = (res.get("distances") or [[]])[0] or []
|
| 720 |
+
out = []
|
| 721 |
+
for i, cid in enumerate(ids):
|
| 722 |
+
content = (docs[i] if i < len(docs) else "") or ""
|
| 723 |
+
if not content.strip():
|
| 724 |
+
continue
|
| 725 |
+
md = metas[i] if i < len(metas) and isinstance(metas[i], dict) else {}
|
| 726 |
+
dist = float(dists[i]) if i < len(dists) and dists[i] is not None else 2.0
|
| 727 |
+
out.append({"id": cid, "content": content, "metadata": md, "_score": distance_to_similarity(dist, space)})
|
| 728 |
+
out.sort(key=lambda d: d["_score"], reverse=True)
|
| 729 |
+
return out
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
def study_context(library_path: str, focus: str, include_subject: bool) -> tuple[str | None, str | None]:
|
| 733 |
+
"""Study-tool context from a library PDF (plus short parts of its course), like the notes version."""
|
| 734 |
+
file_path, subject = scope_of(library_path)
|
| 735 |
+
if not subject:
|
| 736 |
+
return None, "Open a course PDF first."
|
| 737 |
+
ready = sorted(p for p, m in indexed_files().items() if m.get("subject") == subject and m.get("status") == "ok")
|
| 738 |
+
parts = [f"Focus: {focus}", f"Course: {subject_label(subject)}"]
|
| 739 |
+
if file_path:
|
| 740 |
+
main = document_text(file_path)
|
| 741 |
+
if not main:
|
| 742 |
+
return None, NOT_READY
|
| 743 |
+
parts += [f"Primary file: {label_of(file_path)}", "", "--- PRIMARY FILE CONTENT ---", main[:35000]]
|
| 744 |
+
extras, budget, per_file = ([p for p in ready if p != file_path] if include_subject else []), 25000, 3500
|
| 745 |
+
else:
|
| 746 |
+
if not ready:
|
| 747 |
+
return None, NOT_READY
|
| 748 |
+
parts += ["", "--- PRIMARY FILE CONTENT ---"]
|
| 749 |
+
extras, budget, per_file = ready, 50000, max(1500, 50000 // len(ready))
|
| 750 |
+
added: list[str] = []
|
| 751 |
+
for p in extras:
|
| 752 |
+
if budget <= 0:
|
| 753 |
+
break
|
| 754 |
+
text = document_text(p)
|
| 755 |
+
if not text:
|
| 756 |
+
continue
|
| 757 |
+
piece = text[: min(per_file, budget)]
|
| 758 |
+
added.append(f"--- {'COURSE SUPPORTING FILE' if file_path else 'FILE'}: {label_of(p)} ---\n{piece}")
|
| 759 |
+
budget -= len(piece)
|
| 760 |
+
if added:
|
| 761 |
+
if file_path:
|
| 762 |
+
parts += ["", "--- OPTIONAL SAME-COURSE SUPPORT ---"]
|
| 763 |
+
parts.append("\n\n".join(added))
|
| 764 |
+
elif not file_path:
|
| 765 |
+
return None, NOT_READY
|
| 766 |
+
return "\n".join(parts)[:60000], None
|
backend/llm_pipeline.py
CHANGED
|
@@ -1,13 +1,18 @@
|
|
| 1 |
"""LLM + OCR: Sarvam AI — Document Intelligence (Sarvam Vision) + Chat Completions."""
|
| 2 |
import json
|
|
|
|
| 3 |
import os
|
|
|
|
| 4 |
import re
|
| 5 |
import tempfile
|
|
|
|
| 6 |
import zipfile
|
| 7 |
-
from typing import Any
|
| 8 |
|
| 9 |
import httpx
|
| 10 |
|
|
|
|
|
|
|
| 11 |
# Chat models (see https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/chat-completion/overview)
|
| 12 |
_DEFAULT_MODEL_RAG = "sarvam-105b"
|
| 13 |
_DEFAULT_MODEL_STUDY = "sarvam-30b"
|
|
@@ -20,6 +25,35 @@ _GROUNDING_STOPWORDS = {
|
|
| 20 |
}
|
| 21 |
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
def _sarvam_api_key() -> str | None:
|
| 24 |
k = os.getenv("SARVAM_API_KEY")
|
| 25 |
return k.strip() if k else None
|
|
@@ -72,6 +106,11 @@ def _sarvam_chat_complete(
|
|
| 72 |
if not choices:
|
| 73 |
return None, "no choices in response"
|
| 74 |
content = (choices[0].get("message") or {}).get("content")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
if content is None or not str(content).strip():
|
| 76 |
return None, "empty model content"
|
| 77 |
return str(content).strip(), None
|
|
@@ -119,145 +158,116 @@ def _extract_markdown_from_output_zip(zip_path: str) -> str:
|
|
| 119 |
return z.read(pick).decode("utf-8", errors="replace").strip()
|
| 120 |
|
| 121 |
|
| 122 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
"""
|
| 124 |
-
OCR / layout text via Sarvam Document Intelligence (Sarvam Vision).
|
| 125 |
See: https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/document-intelligence/overview
|
| 126 |
"""
|
| 127 |
key = _sarvam_api_key()
|
| 128 |
if not key:
|
| 129 |
-
return None, "SARVAM_API_KEY not configured"
|
| 130 |
try:
|
| 131 |
from sarvamai import SarvamAI
|
| 132 |
except ImportError:
|
| 133 |
-
return None, "sarvamai package not installed (pip install sarvamai)"
|
| 134 |
|
| 135 |
-
raw_bytes, suffix =
|
| 136 |
-
|
| 137 |
tmp_zip: str | None = None
|
| 138 |
timeout = float(os.getenv("SARVAM_DOC_INTEL_TIMEOUT", "180"))
|
| 139 |
try:
|
| 140 |
-
fd,
|
| 141 |
os.write(fd, raw_bytes)
|
| 142 |
os.close(fd)
|
| 143 |
-
fd = -1
|
| 144 |
-
|
| 145 |
client = SarvamAI(api_subscription_key=key, timeout=timeout)
|
| 146 |
lang = os.getenv("SARVAM_DOC_INTEL_LANGUAGE", "en-IN").strip()
|
| 147 |
job = client.document_intelligence.create_job(language=lang, output_format="md")
|
| 148 |
-
job.upload_file(
|
| 149 |
job.start()
|
| 150 |
status = job.wait_until_complete(timeout=timeout)
|
| 151 |
state = str(getattr(status, "job_state", "") or "")
|
| 152 |
if state not in ("Completed", "PartiallyCompleted"):
|
| 153 |
-
return None, f"Document intelligence job state: {state or 'unknown'}"
|
| 154 |
-
|
| 155 |
zfd, tmp_zip = tempfile.mkstemp(suffix=".zip")
|
| 156 |
os.close(zfd)
|
| 157 |
job.download_output(tmp_zip)
|
| 158 |
text = _extract_markdown_from_output_zip(tmp_zip)
|
| 159 |
if not text:
|
| 160 |
-
return None, "empty document intelligence output"
|
| 161 |
-
return text, None
|
| 162 |
-
except TimeoutError as e:
|
| 163 |
-
return None, str(e)
|
| 164 |
except Exception as e:
|
| 165 |
-
|
|
|
|
| 166 |
finally:
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
try:
|
| 174 |
-
os.unlink(tmp_zip)
|
| 175 |
-
except OSError:
|
| 176 |
-
pass
|
| 177 |
|
| 178 |
|
| 179 |
def transcribe_handwritten_image(image_bytes: bytes, mime: str = "image/jpeg") -> tuple[str | None, str | None]:
|
| 180 |
"""Sarvam Vision (Document Intelligence) → markdown/plain text from note images."""
|
| 181 |
-
return
|
| 182 |
|
| 183 |
|
| 184 |
def transcribe_document_bytes(file_bytes: bytes, mime: str = "application/pdf") -> tuple[str | None, str | None]:
|
| 185 |
"""Sarvam Vision (Document Intelligence) OCR for uploaded PDFs/images."""
|
| 186 |
-
|
| 187 |
-
if not key:
|
| 188 |
-
return None, "SARVAM_API_KEY not configured"
|
| 189 |
-
try:
|
| 190 |
-
from sarvamai import SarvamAI
|
| 191 |
-
except ImportError:
|
| 192 |
-
return None, "sarvamai package not installed (pip install sarvamai)"
|
| 193 |
-
raw_bytes, suffix = _prepare_document_for_document_intel(file_bytes, mime)
|
| 194 |
-
tmp_file: str | None = None
|
| 195 |
-
tmp_zip: str | None = None
|
| 196 |
-
timeout = float(os.getenv("SARVAM_DOC_INTEL_TIMEOUT", "180"))
|
| 197 |
-
try:
|
| 198 |
-
fd, tmp_file = tempfile.mkstemp(suffix=suffix)
|
| 199 |
-
os.write(fd, raw_bytes)
|
| 200 |
-
os.close(fd)
|
| 201 |
-
client = SarvamAI(api_subscription_key=key, timeout=timeout)
|
| 202 |
-
lang = os.getenv("SARVAM_DOC_INTEL_LANGUAGE", "en-IN").strip()
|
| 203 |
-
job = client.document_intelligence.create_job(language=lang, output_format="md")
|
| 204 |
-
job.upload_file(tmp_file)
|
| 205 |
-
job.start()
|
| 206 |
-
status = job.wait_until_complete(timeout=timeout)
|
| 207 |
-
state = str(getattr(status, "job_state", "") or "")
|
| 208 |
-
if state not in ("Completed", "PartiallyCompleted"):
|
| 209 |
-
return None, f"Document intelligence job state: {state or 'unknown'}"
|
| 210 |
-
zfd, tmp_zip = tempfile.mkstemp(suffix=".zip")
|
| 211 |
-
os.close(zfd)
|
| 212 |
-
job.download_output(tmp_zip)
|
| 213 |
-
text = _extract_markdown_from_output_zip(tmp_zip)
|
| 214 |
-
if not text:
|
| 215 |
-
return None, "empty document intelligence output"
|
| 216 |
-
return text, None
|
| 217 |
-
except TimeoutError as e:
|
| 218 |
-
return None, str(e)
|
| 219 |
-
except Exception as e:
|
| 220 |
-
return None, str(e)
|
| 221 |
-
finally:
|
| 222 |
-
if tmp_file and os.path.isfile(tmp_file):
|
| 223 |
-
try:
|
| 224 |
-
os.unlink(tmp_file)
|
| 225 |
-
except OSError:
|
| 226 |
-
pass
|
| 227 |
-
if tmp_zip and os.path.isfile(tmp_zip):
|
| 228 |
-
try:
|
| 229 |
-
os.unlink(tmp_zip)
|
| 230 |
-
except OSError:
|
| 231 |
-
pass
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
def sarvam_general_answer(question: str) -> tuple[str | None, str | None]:
|
| 235 |
-
"""Answer without retrieving text from Chroma (no RAG / no stored course excerpts)."""
|
| 236 |
-
messages: list[dict[str, str]] = [
|
| 237 |
-
{
|
| 238 |
-
"role": "system",
|
| 239 |
-
"content": (
|
| 240 |
-
"You are a clear, accurate teaching assistant. Answer the student's question directly. "
|
| 241 |
-
"If essential information is missing, say what you would need to know."
|
| 242 |
-
),
|
| 243 |
-
},
|
| 244 |
-
{"role": "user", "content": question},
|
| 245 |
-
]
|
| 246 |
-
return _sarvam_chat_complete(
|
| 247 |
-
messages,
|
| 248 |
-
model=_model_rag(),
|
| 249 |
-
max_tokens=8192,
|
| 250 |
-
temperature=0.3,
|
| 251 |
-
)
|
| 252 |
|
| 253 |
|
| 254 |
-
def
|
| 255 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
ctx = (context or "").strip()[:60000]
|
| 257 |
q = (question or "").strip()
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
messages: list[dict[str, str]] = [
|
| 261 |
{
|
| 262 |
"role": "system",
|
| 263 |
"content": (
|
|
@@ -267,6 +277,7 @@ def sarvam_rag_answer(question: str, context: str) -> tuple[str | None, str | No
|
|
| 267 |
"- Identify the subject/topic from the notes (e.g. Machine Learning, Linear Algebra, Operating Systems).\n"
|
| 268 |
"- ALWAYS answer the student's question — never refuse or say 'not in notes'.\n"
|
| 269 |
"- When the notes contain the answer, cite specific details from them.\n"
|
|
|
|
| 270 |
"- When the notes are incomplete, supplement with correct, textbook-level knowledge for THAT subject.\n"
|
| 271 |
" Mark such additions with '📖 Beyond notes:' so the student knows.\n"
|
| 272 |
"- NEVER drift to unrelated subjects. If asked about something outside the course scope, "
|
|
@@ -275,7 +286,8 @@ def sarvam_rag_answer(question: str, context: str) -> tuple[str | None, str | No
|
|
| 275 |
"- Explain like a great tutor: clear, concise, with examples.\n"
|
| 276 |
"- For problem-solving: show step-by-step working.\n"
|
| 277 |
"- For tricky exam practice: generate 5-8 challenging questions with concise answer keys.\n"
|
| 278 |
-
"- Use bullet points
|
|
|
|
| 279 |
"- Do not claim inability to access files or notes."
|
| 280 |
),
|
| 281 |
},
|
|
@@ -288,14 +300,67 @@ def sarvam_rag_answer(question: str, context: str) -> tuple[str | None, str | No
|
|
| 288 |
),
|
| 289 |
},
|
| 290 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
return _sarvam_chat_complete(
|
| 292 |
-
|
| 293 |
model=_model_rag(),
|
| 294 |
max_tokens=4096,
|
| 295 |
temperature=0.3,
|
| 296 |
)
|
| 297 |
|
| 298 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
def _parse_json_loose(raw: str) -> Any:
|
| 300 |
raw = raw.strip()
|
| 301 |
raw = re.sub(r"^```(?:json)?\s*", "", raw)
|
|
@@ -375,10 +440,14 @@ def _validate_mcq_smart(items: Any, n: int) -> list[dict[str, Any]] | None:
|
|
| 375 |
if any(not o for o in norm_opts):
|
| 376 |
continue
|
| 377 |
source = str(it.get("source") or "notes").strip()
|
|
|
|
|
|
|
|
|
|
| 378 |
cleaned.append({
|
| 379 |
"question": q,
|
| 380 |
-
"options": norm_opts,
|
| 381 |
-
"answer_index": ai_i,
|
|
|
|
| 382 |
"source": source,
|
| 383 |
})
|
| 384 |
return cleaned if len(cleaned) >= 1 else None
|
|
@@ -395,56 +464,7 @@ def _coerce_study_list(parsed: Any) -> list | None:
|
|
| 395 |
return None
|
| 396 |
|
| 397 |
|
| 398 |
-
def
|
| 399 |
-
b = (body or "").strip()
|
| 400 |
-
if len(b) < 12:
|
| 401 |
-
return []
|
| 402 |
-
chunks = re.split(r"\n{2,}|(?<=[.!?])\s+", b)
|
| 403 |
-
parts = [p.strip() for p in chunks if len(p.strip()) >= 25]
|
| 404 |
-
out: list[dict[str, str]] = []
|
| 405 |
-
for i in range(0, len(parts), 2):
|
| 406 |
-
if len(out) >= n:
|
| 407 |
-
break
|
| 408 |
-
front = parts[i][:220]
|
| 409 |
-
back = (parts[i + 1] if i + 1 < len(parts) else parts[i])[:400]
|
| 410 |
-
ev = parts[i][: min(180, len(parts[i]))]
|
| 411 |
-
if len(ev) < 12:
|
| 412 |
-
ev = b[:120]
|
| 413 |
-
if len(front) < 3 or len(back) < 3:
|
| 414 |
-
continue
|
| 415 |
-
out.append({"front": front, "back": back, "evidence": ev})
|
| 416 |
-
if not out:
|
| 417 |
-
head = b[: min(400, len(b))]
|
| 418 |
-
ev = b[: min(120, len(b))]
|
| 419 |
-
if len(ev) >= 12:
|
| 420 |
-
out.append({"front": "Notes excerpt", "back": head, "evidence": ev})
|
| 421 |
-
return out[:n]
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
def _synthetic_mcq_from_body(body: str, n: int) -> list[dict[str, Any]]:
|
| 425 |
-
b = (body or "").strip()
|
| 426 |
-
if len(b) < 12:
|
| 427 |
-
return []
|
| 428 |
-
sentences = [s.strip() for s in re.split(r"[.!?\n]+", b) if len(s.strip()) > 35]
|
| 429 |
-
out: list[dict[str, Any]] = []
|
| 430 |
-
for s in sentences[:n]:
|
| 431 |
-
q = f"Which statement matches the notes? {s[:100]}…"
|
| 432 |
-
o0 = s[: min(90, len(s))] + ("…" if len(s) > 90 else "")
|
| 433 |
-
opts = [
|
| 434 |
-
o0,
|
| 435 |
-
"The notes do not discuss this topic.",
|
| 436 |
-
"The opposite of what the notes state.",
|
| 437 |
-
"None of the above.",
|
| 438 |
-
]
|
| 439 |
-
ev = s[: min(200, len(s))]
|
| 440 |
-
if len(ev) < 12:
|
| 441 |
-
ev = b[:120]
|
| 442 |
-
out.append({"question": q[:400], "options": opts, "answer_index": 0, "evidence": ev})
|
| 443 |
-
return out
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
def cheap_study_json(context: str, task: str, n: int) -> tuple[Any, str | None]:
|
| 448 |
ctx = context[:60000]
|
| 449 |
body = _primary_body_from_study_ctx(ctx)
|
| 450 |
keywords = _context_keywords(body or ctx)
|
|
@@ -463,7 +483,7 @@ def cheap_study_json(context: str, task: str, n: int) -> tuple[Any, str | None]:
|
|
| 463 |
f" and application/problem-solving cards.\n"
|
| 464 |
f"5. 'front' = question or prompt. 'back' = concise, correct answer.\n"
|
| 465 |
f"6. 'source' = 'notes' if from the notes, 'subject_knowledge' if extended.\n"
|
| 466 |
-
f"7. Output ONLY a JSON array. No markdown fence, no extra text.\n"
|
| 467 |
f" Each object: {{\"front\": str, \"back\": str, \"source\": str}}\n\n"
|
| 468 |
f"Notes:\n{ctx}"
|
| 469 |
)
|
|
@@ -477,12 +497,17 @@ def cheap_study_json(context: str, task: str, n: int) -> tuple[Any, str | None]:
|
|
| 477 |
f" that commonly appear in exams — but NEVER drift to unrelated subjects.\n"
|
| 478 |
f"4. Mix difficulty: include recall, application, analysis, and tricky 'gotcha' questions.\n"
|
| 479 |
f"5. Each question must have exactly 4 plausible options. Distractors should be realistic, not obviously wrong.\n"
|
| 480 |
-
f"6. '
|
| 481 |
-
f"7.
|
| 482 |
-
f"
|
|
|
|
| 483 |
f"Notes:\n{ctx}"
|
| 484 |
)
|
| 485 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 486 |
last_err = "generation failed"
|
| 487 |
for k in range(3):
|
| 488 |
msg = prompt if k == 0 else (prompt + "\n\nPrevious output had formatting issues. Regenerate valid JSON strictly following the schema.")
|
|
@@ -514,18 +539,12 @@ def cheap_study_json(context: str, task: str, n: int) -> tuple[Any, str | None]:
|
|
| 514 |
except json.JSONDecodeError as e:
|
| 515 |
last_err = f"invalid JSON: {e}"
|
| 516 |
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
syn = _synthetic_flashcards_from_body(primary, n)
|
| 521 |
-
else:
|
| 522 |
-
syn = _synthetic_mcq_from_body(primary, n)
|
| 523 |
-
if syn:
|
| 524 |
-
return syn, None
|
| 525 |
-
return None, last_err
|
| 526 |
|
| 527 |
|
| 528 |
-
def topic_summary(context: str) -> tuple[str | None, str | None]:
|
| 529 |
"""Generate a concise 100-150 word summary covering all key topics from the notes."""
|
| 530 |
ctx = (context or "").strip()[:60000]
|
| 531 |
body = _primary_body_from_study_ctx(ctx)
|
|
@@ -542,7 +561,8 @@ def topic_summary(context: str) -> tuple[str | None, str | None]:
|
|
| 542 |
"3. Structure: start with the overarching topic, then list key concepts in logical order.\n"
|
| 543 |
"4. Do NOT add content from outside the notes — summarize only what is provided.\n"
|
| 544 |
"5. Write in plain text paragraphs (no bullet points, no JSON, no markdown headers).\n"
|
| 545 |
-
"6. Aim for exactly 100-150 words. Be dense and information-rich.\n
|
|
|
|
| 546 |
f"Notes:\n{ctx}"
|
| 547 |
)
|
| 548 |
|
|
@@ -568,11 +588,7 @@ def topic_summary(context: str) -> tuple[str | None, str | None]:
|
|
| 568 |
return text, None
|
| 569 |
last_err = "summary too short"
|
| 570 |
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
fallback = ". ".join(sentences[:8])
|
| 574 |
-
if len(fallback) >= 40:
|
| 575 |
-
return fallback[:600] + ".", None
|
| 576 |
-
return None, last_err
|
| 577 |
|
| 578 |
|
|
|
|
| 1 |
"""LLM + OCR: Sarvam AI — Document Intelligence (Sarvam Vision) + Chat Completions."""
|
| 2 |
import json
|
| 3 |
+
import logging
|
| 4 |
import os
|
| 5 |
+
import random
|
| 6 |
import re
|
| 7 |
import tempfile
|
| 8 |
+
import threading
|
| 9 |
import zipfile
|
| 10 |
+
from typing import Any, Iterator
|
| 11 |
|
| 12 |
import httpx
|
| 13 |
|
| 14 |
+
logger = logging.getLogger(__name__)
|
| 15 |
+
|
| 16 |
# Chat models (see https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/chat-completion/overview)
|
| 17 |
_DEFAULT_MODEL_RAG = "sarvam-105b"
|
| 18 |
_DEFAULT_MODEL_STUDY = "sarvam-30b"
|
|
|
|
| 25 |
}
|
| 26 |
|
| 27 |
|
| 28 |
+
_usage = threading.local()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _add_usage(prompt_tokens: int, completion_tokens: int) -> None:
|
| 32 |
+
_usage.prompt = getattr(_usage, "prompt", 0) + int(prompt_tokens or 0)
|
| 33 |
+
_usage.completion = getattr(_usage, "completion", 0) + int(completion_tokens or 0)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def estimate_tokens(text: str) -> int:
|
| 37 |
+
"""Rough token count (about 4 characters per token) when the API doesn't report usage."""
|
| 38 |
+
return max(1, len(text or "") // 4)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def take_usage() -> dict:
|
| 42 |
+
"""AI tokens used by chat calls made in this thread since the last call (then resets to zero)."""
|
| 43 |
+
out = {"prompt_tokens": getattr(_usage, "prompt", 0), "completion_tokens": getattr(_usage, "completion", 0)}
|
| 44 |
+
_usage.prompt = _usage.completion = 0
|
| 45 |
+
return out
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def language_instruction(language: str | None) -> str:
|
| 49 |
+
if not language or language == "English":
|
| 50 |
+
return ""
|
| 51 |
+
return (
|
| 52 |
+
f"Write all of your output in {language}. Keep formulas, code, units and standard technical "
|
| 53 |
+
"terms as they are (English or LaTeX)."
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
def _sarvam_api_key() -> str | None:
|
| 58 |
k = os.getenv("SARVAM_API_KEY")
|
| 59 |
return k.strip() if k else None
|
|
|
|
| 106 |
if not choices:
|
| 107 |
return None, "no choices in response"
|
| 108 |
content = (choices[0].get("message") or {}).get("content")
|
| 109 |
+
usage = data.get("usage") if isinstance(data.get("usage"), dict) else {}
|
| 110 |
+
_add_usage(
|
| 111 |
+
usage.get("prompt_tokens") or estimate_tokens(json.dumps(messages)),
|
| 112 |
+
usage.get("completion_tokens") or estimate_tokens(str(content or "")),
|
| 113 |
+
)
|
| 114 |
if content is None or not str(content).strip():
|
| 115 |
return None, "empty model content"
|
| 116 |
return str(content).strip(), None
|
|
|
|
| 158 |
return z.read(pick).decode("utf-8", errors="replace").strip()
|
| 159 |
|
| 160 |
|
| 161 |
+
def _strings_in(value) -> list[str]:
|
| 162 |
+
if isinstance(value, str):
|
| 163 |
+
return [value]
|
| 164 |
+
if isinstance(value, dict):
|
| 165 |
+
out = []
|
| 166 |
+
for k in ("text", "content", "markdown"):
|
| 167 |
+
if isinstance(value.get(k), str):
|
| 168 |
+
out.append(value[k])
|
| 169 |
+
for v in value.values():
|
| 170 |
+
if isinstance(v, (dict, list)):
|
| 171 |
+
out.extend(_strings_in(v))
|
| 172 |
+
return out
|
| 173 |
+
if isinstance(value, list):
|
| 174 |
+
return [s for v in value for s in _strings_in(v)]
|
| 175 |
+
return []
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _page_texts_from_output_zip(zip_path: str) -> list[str]:
|
| 179 |
+
"""Per-page text from metadata/page_NNN.json files in a Document Intelligence output zip ([] if absent)."""
|
| 180 |
+
pages: list[tuple[int, str]] = []
|
| 181 |
+
try:
|
| 182 |
+
with zipfile.ZipFile(zip_path, "r") as z:
|
| 183 |
+
for name in z.namelist():
|
| 184 |
+
m = re.search(r"page_(\d+)\.json$", name)
|
| 185 |
+
if not m:
|
| 186 |
+
continue
|
| 187 |
+
try:
|
| 188 |
+
data = json.loads(z.read(name).decode("utf-8", errors="replace"))
|
| 189 |
+
except json.JSONDecodeError:
|
| 190 |
+
continue
|
| 191 |
+
pages.append((int(m.group(1)), " ".join(_strings_in(data))))
|
| 192 |
+
except zipfile.BadZipFile:
|
| 193 |
+
return []
|
| 194 |
+
return [text for _, text in sorted(pages)]
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def _document_intelligence(file_bytes: bytes, mime: str) -> tuple[str | None, str | None]:
|
| 198 |
+
text, err, _pages = _document_intelligence_with_pages(file_bytes, mime)
|
| 199 |
+
return text, err
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _document_intelligence_with_pages(file_bytes: bytes, mime: str) -> tuple[str | None, str | None, list[str]]:
|
| 203 |
"""
|
| 204 |
+
OCR / layout text via Sarvam Document Intelligence (Sarvam Vision) for a PDF or an image.
|
| 205 |
See: https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/document-intelligence/overview
|
| 206 |
"""
|
| 207 |
key = _sarvam_api_key()
|
| 208 |
if not key:
|
| 209 |
+
return None, "SARVAM_API_KEY not configured", []
|
| 210 |
try:
|
| 211 |
from sarvamai import SarvamAI
|
| 212 |
except ImportError:
|
| 213 |
+
return None, "sarvamai package not installed (pip install sarvamai)", []
|
| 214 |
|
| 215 |
+
raw_bytes, suffix = _prepare_document_for_document_intel(file_bytes, mime)
|
| 216 |
+
tmp_file: str | None = None
|
| 217 |
tmp_zip: str | None = None
|
| 218 |
timeout = float(os.getenv("SARVAM_DOC_INTEL_TIMEOUT", "180"))
|
| 219 |
try:
|
| 220 |
+
fd, tmp_file = tempfile.mkstemp(suffix=suffix)
|
| 221 |
os.write(fd, raw_bytes)
|
| 222 |
os.close(fd)
|
|
|
|
|
|
|
| 223 |
client = SarvamAI(api_subscription_key=key, timeout=timeout)
|
| 224 |
lang = os.getenv("SARVAM_DOC_INTEL_LANGUAGE", "en-IN").strip()
|
| 225 |
job = client.document_intelligence.create_job(language=lang, output_format="md")
|
| 226 |
+
job.upload_file(tmp_file)
|
| 227 |
job.start()
|
| 228 |
status = job.wait_until_complete(timeout=timeout)
|
| 229 |
state = str(getattr(status, "job_state", "") or "")
|
| 230 |
if state not in ("Completed", "PartiallyCompleted"):
|
| 231 |
+
return None, f"Document intelligence job state: {state or 'unknown'}", []
|
|
|
|
| 232 |
zfd, tmp_zip = tempfile.mkstemp(suffix=".zip")
|
| 233 |
os.close(zfd)
|
| 234 |
job.download_output(tmp_zip)
|
| 235 |
text = _extract_markdown_from_output_zip(tmp_zip)
|
| 236 |
if not text:
|
| 237 |
+
return None, "empty document intelligence output", []
|
| 238 |
+
return text, None, _page_texts_from_output_zip(tmp_zip)
|
|
|
|
|
|
|
| 239 |
except Exception as e:
|
| 240 |
+
logger.warning("Sarvam document intelligence failed: %s", e)
|
| 241 |
+
return None, str(e), []
|
| 242 |
finally:
|
| 243 |
+
for tmp in (tmp_file, tmp_zip):
|
| 244 |
+
if tmp and os.path.isfile(tmp):
|
| 245 |
+
try:
|
| 246 |
+
os.unlink(tmp)
|
| 247 |
+
except OSError:
|
| 248 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
|
| 251 |
def transcribe_handwritten_image(image_bytes: bytes, mime: str = "image/jpeg") -> tuple[str | None, str | None]:
|
| 252 |
"""Sarvam Vision (Document Intelligence) → markdown/plain text from note images."""
|
| 253 |
+
return _document_intelligence(image_bytes, mime or "image/jpeg")
|
| 254 |
|
| 255 |
|
| 256 |
def transcribe_document_bytes(file_bytes: bytes, mime: str = "application/pdf") -> tuple[str | None, str | None]:
|
| 257 |
"""Sarvam Vision (Document Intelligence) OCR for uploaded PDFs/images."""
|
| 258 |
+
return _document_intelligence(file_bytes, mime)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
|
| 261 |
+
def transcribe_pdf_with_pages(file_bytes: bytes) -> tuple[str | None, str | None, list[str]]:
|
| 262 |
+
"""Like transcribe_document_bytes for a PDF, plus each page's own text (when Sarvam provides it)."""
|
| 263 |
+
return _document_intelligence_with_pages(file_bytes, "application/pdf")
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def _rag_messages(question: str, context: str, language: str = "English") -> list[dict[str, str]]:
|
| 267 |
ctx = (context or "").strip()[:60000]
|
| 268 |
q = (question or "").strip()
|
| 269 |
+
lang = language_instruction(language)
|
| 270 |
+
messages = [
|
|
|
|
| 271 |
{
|
| 272 |
"role": "system",
|
| 273 |
"content": (
|
|
|
|
| 277 |
"- Identify the subject/topic from the notes (e.g. Machine Learning, Linear Algebra, Operating Systems).\n"
|
| 278 |
"- ALWAYS answer the student's question — never refuse or say 'not in notes'.\n"
|
| 279 |
"- When the notes contain the answer, cite specific details from them.\n"
|
| 280 |
+
"- Excerpts marked (main source) come from files the student marked as most reliable; prefer them.\n"
|
| 281 |
"- When the notes are incomplete, supplement with correct, textbook-level knowledge for THAT subject.\n"
|
| 282 |
" Mark such additions with '📖 Beyond notes:' so the student knows.\n"
|
| 283 |
"- NEVER drift to unrelated subjects. If asked about something outside the course scope, "
|
|
|
|
| 286 |
"- Explain like a great tutor: clear, concise, with examples.\n"
|
| 287 |
"- For problem-solving: show step-by-step working.\n"
|
| 288 |
"- For tricky exam practice: generate 5-8 challenging questions with concise answer keys.\n"
|
| 289 |
+
"- Use Markdown: bullet points, short paragraphs, tables when useful.\n"
|
| 290 |
+
"- Write math in LaTeX: $...$ inline and $$...$$ for display equations.\n"
|
| 291 |
"- Do not claim inability to access files or notes."
|
| 292 |
),
|
| 293 |
},
|
|
|
|
| 300 |
),
|
| 301 |
},
|
| 302 |
]
|
| 303 |
+
if lang:
|
| 304 |
+
messages[0]["content"] += "\n- " + lang
|
| 305 |
+
return messages
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def sarvam_rag_answer(question: str, context: str, language: str = "English") -> tuple[str | None, str | None]:
|
| 309 |
+
"""Answer from notes-first context with constrained subject verification."""
|
| 310 |
+
if not (question or "").strip():
|
| 311 |
+
return None, "Empty query"
|
| 312 |
return _sarvam_chat_complete(
|
| 313 |
+
_rag_messages(question, context, language),
|
| 314 |
model=_model_rag(),
|
| 315 |
max_tokens=4096,
|
| 316 |
temperature=0.3,
|
| 317 |
)
|
| 318 |
|
| 319 |
|
| 320 |
+
class LLMError(Exception):
|
| 321 |
+
"""The AI service failed; the message is safe to log, not meant for students."""
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def sarvam_rag_answer_stream(question: str, context: str, language: str = "English") -> Iterator[str]:
|
| 325 |
+
"""
|
| 326 |
+
Same answer as sarvam_rag_answer, yielded piece by piece as the model writes it
|
| 327 |
+
(server-sent events, `stream: true`). Raises LLMError if the request fails.
|
| 328 |
+
"""
|
| 329 |
+
key = _sarvam_api_key()
|
| 330 |
+
if not key:
|
| 331 |
+
raise LLMError("SARVAM_API_KEY not configured")
|
| 332 |
+
url = f"{_chat_base_url()}/v1/chat/completions"
|
| 333 |
+
payload = {
|
| 334 |
+
"model": _model_rag(),
|
| 335 |
+
"messages": _rag_messages(question, context, language),
|
| 336 |
+
"max_tokens": 4096,
|
| 337 |
+
"temperature": 0.3,
|
| 338 |
+
"stream": True,
|
| 339 |
+
}
|
| 340 |
+
headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
|
| 341 |
+
try:
|
| 342 |
+
with httpx.stream("POST", url, headers=headers, json=payload, timeout=300.0) as r:
|
| 343 |
+
if r.status_code >= 400:
|
| 344 |
+
r.read()
|
| 345 |
+
raise LLMError(f"HTTP {r.status_code}: {r.text[:300]}")
|
| 346 |
+
for line in r.iter_lines():
|
| 347 |
+
if not line or not line.startswith("data:"):
|
| 348 |
+
continue
|
| 349 |
+
data = line[5:].strip()
|
| 350 |
+
if data == "[DONE]":
|
| 351 |
+
break
|
| 352 |
+
try:
|
| 353 |
+
chunk = json.loads(data)
|
| 354 |
+
except json.JSONDecodeError:
|
| 355 |
+
continue
|
| 356 |
+
for choice in chunk.get("choices") or []:
|
| 357 |
+
piece = (choice.get("delta") or {}).get("content")
|
| 358 |
+
if piece:
|
| 359 |
+
yield piece
|
| 360 |
+
except httpx.HTTPError as e:
|
| 361 |
+
raise LLMError(str(e)) from e
|
| 362 |
+
|
| 363 |
+
|
| 364 |
def _parse_json_loose(raw: str) -> Any:
|
| 365 |
raw = raw.strip()
|
| 366 |
raw = re.sub(r"^```(?:json)?\s*", "", raw)
|
|
|
|
| 440 |
if any(not o for o in norm_opts):
|
| 441 |
continue
|
| 442 |
source = str(it.get("source") or "notes").strip()
|
| 443 |
+
explanation = str(it.get("explanation") or "").strip()
|
| 444 |
+
order = list(range(4))
|
| 445 |
+
random.shuffle(order)
|
| 446 |
cleaned.append({
|
| 447 |
"question": q,
|
| 448 |
+
"options": [norm_opts[i] for i in order],
|
| 449 |
+
"answer_index": order.index(ai_i),
|
| 450 |
+
"explanation": explanation,
|
| 451 |
"source": source,
|
| 452 |
})
|
| 453 |
return cleaned if len(cleaned) >= 1 else None
|
|
|
|
| 464 |
return None
|
| 465 |
|
| 466 |
|
| 467 |
+
def cheap_study_json(context: str, task: str, n: int, language: str = "English") -> tuple[Any, str | None]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 468 |
ctx = context[:60000]
|
| 469 |
body = _primary_body_from_study_ctx(ctx)
|
| 470 |
keywords = _context_keywords(body or ctx)
|
|
|
|
| 483 |
f" and application/problem-solving cards.\n"
|
| 484 |
f"5. 'front' = question or prompt. 'back' = concise, correct answer.\n"
|
| 485 |
f"6. 'source' = 'notes' if from the notes, 'subject_knowledge' if extended.\n"
|
| 486 |
+
f"7. Write math in LaTeX ($...$). Output ONLY a JSON array. No markdown fence, no extra text.\n"
|
| 487 |
f" Each object: {{\"front\": str, \"back\": str, \"source\": str}}\n\n"
|
| 488 |
f"Notes:\n{ctx}"
|
| 489 |
)
|
|
|
|
| 497 |
f" that commonly appear in exams — but NEVER drift to unrelated subjects.\n"
|
| 498 |
f"4. Mix difficulty: include recall, application, analysis, and tricky 'gotcha' questions.\n"
|
| 499 |
f"5. Each question must have exactly 4 plausible options. Distractors should be realistic, not obviously wrong.\n"
|
| 500 |
+
f"6. 'explanation' = one or two sentences on why the correct option is right (and the tempting wrong one is wrong).\n"
|
| 501 |
+
f"7. 'source' = 'notes' if from the notes, 'subject_knowledge' if extended.\n"
|
| 502 |
+
f"8. Write math in LaTeX ($...$). Output ONLY a JSON array. No markdown fence, no extra text.\n"
|
| 503 |
+
f" Each object: {{\"question\": str, \"options\": [str,str,str,str], \"answer_index\": 0-3, \"explanation\": str, \"source\": str}}\n\n"
|
| 504 |
f"Notes:\n{ctx}"
|
| 505 |
)
|
| 506 |
|
| 507 |
+
lang = language_instruction(language)
|
| 508 |
+
if lang:
|
| 509 |
+
prompt = prompt.replace("\n\nNotes:\n", f"\n\n{lang} JSON keys stay in English.\n\nNotes:\n", 1)
|
| 510 |
+
label = "flashcards" if task == "flashcards" else "MCQs"
|
| 511 |
last_err = "generation failed"
|
| 512 |
for k in range(3):
|
| 513 |
msg = prompt if k == 0 else (prompt + "\n\nPrevious output had formatting issues. Regenerate valid JSON strictly following the schema.")
|
|
|
|
| 539 |
except json.JSONDecodeError as e:
|
| 540 |
last_err = f"invalid JSON: {e}"
|
| 541 |
|
| 542 |
+
# Never invent study items ourselves: a wrong "answer key" is worse than a clear error.
|
| 543 |
+
logger.warning("Study generation (%s) failed after retries: %s", task, last_err)
|
| 544 |
+
return None, f"The AI couldn't generate {label} right now. Please try again."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 545 |
|
| 546 |
|
| 547 |
+
def topic_summary(context: str, language: str = "English") -> tuple[str | None, str | None]:
|
| 548 |
"""Generate a concise 100-150 word summary covering all key topics from the notes."""
|
| 549 |
ctx = (context or "").strip()[:60000]
|
| 550 |
body = _primary_body_from_study_ctx(ctx)
|
|
|
|
| 561 |
"3. Structure: start with the overarching topic, then list key concepts in logical order.\n"
|
| 562 |
"4. Do NOT add content from outside the notes — summarize only what is provided.\n"
|
| 563 |
"5. Write in plain text paragraphs (no bullet points, no JSON, no markdown headers).\n"
|
| 564 |
+
"6. Aim for exactly 100-150 words. Be dense and information-rich.\n"
|
| 565 |
+
f"{language_instruction(language)}\n\n"
|
| 566 |
f"Notes:\n{ctx}"
|
| 567 |
)
|
| 568 |
|
|
|
|
| 588 |
return text, None
|
| 589 |
last_err = "summary too short"
|
| 590 |
|
| 591 |
+
logger.warning("Summary generation failed after retries: %s", last_err)
|
| 592 |
+
return None, "The AI couldn't write a summary right now. Please try again."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 593 |
|
| 594 |
|
backend/mailer.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sending password-reset emails over SMTP. Enabled only when SMTP_HOST and SMTP_FROM are set."""
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import smtplib
|
| 5 |
+
from email.message import EmailMessage
|
| 6 |
+
|
| 7 |
+
logger = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _env(name: str, default: str = "") -> str:
|
| 11 |
+
return (os.getenv(name) or default).strip()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def is_configured() -> bool:
|
| 15 |
+
return bool(_env("SMTP_HOST") and _env("SMTP_FROM"))
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def send_email(to: str, subject: str, body: str) -> None:
|
| 19 |
+
"""Send a plain-text email. Raises on failure."""
|
| 20 |
+
host = _env("SMTP_HOST")
|
| 21 |
+
port = int(_env("SMTP_PORT", "587") or "587")
|
| 22 |
+
username = _env("SMTP_USERNAME")
|
| 23 |
+
password = _env("SMTP_PASSWORD")
|
| 24 |
+
starttls = _env("SMTP_STARTTLS", "true").lower() in ("1", "true", "yes")
|
| 25 |
+
|
| 26 |
+
msg = EmailMessage()
|
| 27 |
+
msg["From"] = _env("SMTP_FROM")
|
| 28 |
+
msg["To"] = to
|
| 29 |
+
msg["Subject"] = subject
|
| 30 |
+
msg.set_content(body)
|
| 31 |
+
|
| 32 |
+
smtp_cls = smtplib.SMTP_SSL if port == 465 else smtplib.SMTP
|
| 33 |
+
with smtp_cls(host, port, timeout=20) as smtp:
|
| 34 |
+
if starttls and port != 465:
|
| 35 |
+
smtp.starttls()
|
| 36 |
+
if username:
|
| 37 |
+
smtp.login(username, password)
|
| 38 |
+
smtp.send_message(msg)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def send_password_reset(to: str, reset_link: str) -> None:
|
| 42 |
+
body = (
|
| 43 |
+
"Someone asked to reset the password for your NoteScanner account.\n\n"
|
| 44 |
+
f"Open this link to choose a new password (it works once and expires in 1 hour):\n{reset_link}\n\n"
|
| 45 |
+
"If you didn't ask for this, you can ignore this email; your password stays the same."
|
| 46 |
+
)
|
| 47 |
+
send_email(to, "Reset your NoteScanner password", body)
|
backend/onenote_sync.py
CHANGED
|
@@ -15,7 +15,7 @@ import httpx
|
|
| 15 |
from backend.chroma_store import onenote_token_get, onenote_token_upsert
|
| 16 |
from backend.chroma_store import user_document_upsert
|
| 17 |
from backend.ingest_api import ingest_text_for_path
|
| 18 |
-
from backend.chroma_store import vfs_get_tree, vfs_set_tree
|
| 19 |
from backend.vfs_tree import tree_add_folder, tree_add_file
|
| 20 |
|
| 21 |
GRAPH_AUTHORIZE_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
|
|
@@ -192,7 +192,7 @@ def _page_to_rel_path(page: dict) -> tuple[str, str]:
|
|
| 192 |
def sync_onenote_pages_to_ingest(user_id: str, max_pages: int = 25) -> dict:
|
| 193 |
access_token, _ = ensure_user_access_token(user_id)
|
| 194 |
pages = _list_onenote_pages(access_token, max_pages=max_pages)
|
| 195 |
-
|
| 196 |
ingested = 0
|
| 197 |
skipped = 0
|
| 198 |
errors: list[str] = []
|
|
@@ -213,20 +213,26 @@ def sync_onenote_pages_to_ingest(user_id: str, max_pages: int = 25) -> dict:
|
|
| 213 |
continue
|
| 214 |
folder = rel_path.rsplit("/", 1)[0]
|
| 215 |
file_name = rel_path.rsplit("/", 1)[-1]
|
| 216 |
-
tree = tree_add_folder(tree, "", folder)
|
| 217 |
-
tree = tree_add_file(tree, folder, file_name)
|
| 218 |
try:
|
| 219 |
user_document_upsert(user_id, rel_path, text, source_title)
|
| 220 |
except Exception:
|
| 221 |
# user_documents is a cache; ingest chunks are the primary retrieval source.
|
| 222 |
pass
|
| 223 |
ingest_text_for_path(user_id, rel_path, source_title, text)
|
|
|
|
| 224 |
ingested += 1
|
| 225 |
except Exception as e:
|
| 226 |
errors.append(str(e))
|
| 227 |
continue
|
| 228 |
|
| 229 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
return {
|
| 231 |
"pages_seen": len(pages),
|
| 232 |
"pages_ingested": ingested,
|
|
|
|
| 15 |
from backend.chroma_store import onenote_token_get, onenote_token_upsert
|
| 16 |
from backend.chroma_store import user_document_upsert
|
| 17 |
from backend.ingest_api import ingest_text_for_path
|
| 18 |
+
from backend.chroma_store import user_lock, vfs_get_tree, vfs_set_tree
|
| 19 |
from backend.vfs_tree import tree_add_folder, tree_add_file
|
| 20 |
|
| 21 |
GRAPH_AUTHORIZE_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
|
|
|
|
| 192 |
def sync_onenote_pages_to_ingest(user_id: str, max_pages: int = 25) -> dict:
|
| 193 |
access_token, _ = ensure_user_access_token(user_id)
|
| 194 |
pages = _list_onenote_pages(access_token, max_pages=max_pages)
|
| 195 |
+
added: list[tuple[str, str]] = []
|
| 196 |
ingested = 0
|
| 197 |
skipped = 0
|
| 198 |
errors: list[str] = []
|
|
|
|
| 213 |
continue
|
| 214 |
folder = rel_path.rsplit("/", 1)[0]
|
| 215 |
file_name = rel_path.rsplit("/", 1)[-1]
|
|
|
|
|
|
|
| 216 |
try:
|
| 217 |
user_document_upsert(user_id, rel_path, text, source_title)
|
| 218 |
except Exception:
|
| 219 |
# user_documents is a cache; ingest chunks are the primary retrieval source.
|
| 220 |
pass
|
| 221 |
ingest_text_for_path(user_id, rel_path, source_title, text)
|
| 222 |
+
added.append((folder, file_name))
|
| 223 |
ingested += 1
|
| 224 |
except Exception as e:
|
| 225 |
errors.append(str(e))
|
| 226 |
continue
|
| 227 |
|
| 228 |
+
if added:
|
| 229 |
+
# Re-read under the lock so uploads made during the sync aren't overwritten.
|
| 230 |
+
with user_lock(user_id):
|
| 231 |
+
tree = vfs_get_tree(user_id)
|
| 232 |
+
for folder, file_name in added:
|
| 233 |
+
tree = tree_add_folder(tree, "", folder)
|
| 234 |
+
tree = tree_add_file(tree, folder, file_name)
|
| 235 |
+
vfs_set_tree(user_id, tree)
|
| 236 |
return {
|
| 237 |
"pages_seen": len(pages),
|
| 238 |
"pages_ingested": ingested,
|
backend/pages.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Page numbers for PDF text, so answers can say "page 7" instead of only the file name.
|
| 3 |
+
|
| 4 |
+
A file's text gets a list of page starts: [(character offset, page number), ...]. Each search chunk
|
| 5 |
+
then records the page its first character is on. When the text comes from PyMuPDF the starts are
|
| 6 |
+
exact; when it comes from Sarvam Vision, each page's own text is found inside the full text.
|
| 7 |
+
"""
|
| 8 |
+
from bisect import bisect_right
|
| 9 |
+
|
| 10 |
+
PageStarts = list[tuple[int, int]]
|
| 11 |
+
|
| 12 |
+
_IGNORED = set("#*_`>|")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def join_pages(page_texts: list[str]) -> tuple[str, PageStarts]:
|
| 16 |
+
"""Join per-page texts into one text and record where each page starts."""
|
| 17 |
+
parts: list[str] = []
|
| 18 |
+
starts: PageStarts = []
|
| 19 |
+
offset = 0
|
| 20 |
+
for number, page in enumerate(page_texts, start=1):
|
| 21 |
+
page = (page or "").strip()
|
| 22 |
+
if not page:
|
| 23 |
+
continue
|
| 24 |
+
if parts:
|
| 25 |
+
parts.append("\n\n")
|
| 26 |
+
offset += 2
|
| 27 |
+
starts.append((offset, number))
|
| 28 |
+
parts.append(page)
|
| 29 |
+
offset += len(page)
|
| 30 |
+
return "".join(parts), starts
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _normalize_with_map(text: str) -> tuple[str, list[int]]:
|
| 34 |
+
"""Lowercase, collapse whitespace and drop markdown symbols, remembering each char's original index."""
|
| 35 |
+
out: list[str] = []
|
| 36 |
+
index_map: list[int] = []
|
| 37 |
+
prev_space = True
|
| 38 |
+
for i, ch in enumerate(text or ""):
|
| 39 |
+
if ch.isspace() or ch in _IGNORED:
|
| 40 |
+
if not prev_space:
|
| 41 |
+
out.append(" ")
|
| 42 |
+
index_map.append(i)
|
| 43 |
+
prev_space = True
|
| 44 |
+
continue
|
| 45 |
+
out.append(ch.lower())
|
| 46 |
+
index_map.append(i)
|
| 47 |
+
prev_space = False
|
| 48 |
+
return "".join(out), index_map
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def anchor_page_starts(full_text: str, page_texts: list[str], snippet_len: int = 40) -> PageStarts | None:
|
| 52 |
+
"""
|
| 53 |
+
Find where each page's text begins inside `full_text` (searching forward, in page order).
|
| 54 |
+
Pages whose start can't be found are merged into the page before. None if nothing useful.
|
| 55 |
+
"""
|
| 56 |
+
pages = [(n, p) for n, p in enumerate(page_texts or [], start=1)]
|
| 57 |
+
if len(pages) < 2:
|
| 58 |
+
return None
|
| 59 |
+
norm, index_map = _normalize_with_map(full_text)
|
| 60 |
+
starts: PageStarts = [(0, pages[0][0])]
|
| 61 |
+
pos = 0
|
| 62 |
+
for number, page in pages[1:]:
|
| 63 |
+
snippet = _normalize_with_map(page)[0].strip()[:snippet_len]
|
| 64 |
+
if len(snippet) < 12:
|
| 65 |
+
continue
|
| 66 |
+
found = norm.find(snippet, pos)
|
| 67 |
+
if found < 0:
|
| 68 |
+
continue
|
| 69 |
+
pos = found
|
| 70 |
+
starts.append((index_map[found], number))
|
| 71 |
+
return starts if len(starts) > 1 else None
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def page_at(offset: int, starts: PageStarts | None) -> int | None:
|
| 75 |
+
if not starts:
|
| 76 |
+
return None
|
| 77 |
+
i = bisect_right([s for s, _ in starts], offset) - 1
|
| 78 |
+
return starts[max(i, 0)][1]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def pdf_page_texts(data: bytes) -> list[str]:
|
| 82 |
+
import fitz # PyMuPDF
|
| 83 |
+
|
| 84 |
+
doc = fitz.open(stream=data, filetype="pdf")
|
| 85 |
+
try:
|
| 86 |
+
return [page.get_text() for page in doc]
|
| 87 |
+
finally:
|
| 88 |
+
doc.close()
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def pdf_page_count(data: bytes) -> int:
|
| 92 |
+
try:
|
| 93 |
+
return len(pdf_page_texts(data))
|
| 94 |
+
except Exception:
|
| 95 |
+
return 1
|
backend/paths.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Virtual-path cleanup and folder-tree reads shared by the routes."""
|
| 2 |
+
import copy
|
| 3 |
+
|
| 4 |
+
from backend.chroma_store import user_lock, vfs_get_tree, vfs_set_tree
|
| 5 |
+
from backend.legacy_migration import migrate_legacy_twin_paths
|
| 6 |
+
from backend.vfs_tree import flatten_file_paths
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def normalize_relative_path(path: str) -> str:
|
| 10 |
+
"""Use forward slashes and strip leading slashes for cross-platform consistency."""
|
| 11 |
+
if not path or not path.strip():
|
| 12 |
+
return ""
|
| 13 |
+
return path.replace("\\", "/").strip("/")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _is_likely_user_id_segment(seg: str) -> bool:
|
| 17 |
+
if not seg:
|
| 18 |
+
return False
|
| 19 |
+
if seg.startswith("guest_"):
|
| 20 |
+
return True
|
| 21 |
+
if len(seg) == 36 and seg.count("-") == 4:
|
| 22 |
+
return True
|
| 23 |
+
return False
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def strip_storage_path(p: str) -> str:
|
| 27 |
+
"""
|
| 28 |
+
Remove legacy server-side prefixes from virtual paths so course folders stay at the root
|
| 29 |
+
(e.g. user_notes/<id>/Course/a.pdf -> Course/a.pdf). Never persist user_notes in vfs.
|
| 30 |
+
"""
|
| 31 |
+
p = normalize_relative_path(p)
|
| 32 |
+
if not p:
|
| 33 |
+
return ""
|
| 34 |
+
parts = [x for x in p.split("/") if x and x != "."]
|
| 35 |
+
while parts and parts[0].lower() == "user_notes":
|
| 36 |
+
parts.pop(0)
|
| 37 |
+
if parts and _is_likely_user_id_segment(parts[0]):
|
| 38 |
+
parts.pop(0)
|
| 39 |
+
return "/".join(parts)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def valid_name(name: str) -> bool:
|
| 43 |
+
"""A single file or folder name: not empty, no slashes, not '.' or '..'."""
|
| 44 |
+
return bool(name) and "/" not in name and "\\" not in name and ".." not in name and name not in (".",)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def parent_of(path: str) -> str:
|
| 48 |
+
return path.rsplit("/", 1)[0] if "/" in path else ""
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def join_path(parent: str, name: str) -> str:
|
| 52 |
+
return f"{parent}/{name}" if parent else name
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _normalize_vfs_tree(tree: list) -> list:
|
| 56 |
+
"""Deep copy of explorer tree with every path passed through strip_storage_path."""
|
| 57 |
+
out = copy.deepcopy(tree or [])
|
| 58 |
+
|
| 59 |
+
def rec(nodes: list) -> None:
|
| 60 |
+
for n in nodes:
|
| 61 |
+
if "path" in n:
|
| 62 |
+
n["path"] = strip_storage_path(str(n.get("path") or ""))
|
| 63 |
+
if n.get("type") == "folder":
|
| 64 |
+
rec(n.get("children") or [])
|
| 65 |
+
|
| 66 |
+
rec(out)
|
| 67 |
+
return out
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def get_vfs_tree_clean(user_id: str) -> list:
|
| 71 |
+
"""Return vfs tree with no user_notes/legacy id prefixes; persist if corrected."""
|
| 72 |
+
raw = vfs_get_tree(user_id)
|
| 73 |
+
fixed = _normalize_vfs_tree(raw)
|
| 74 |
+
if fixed != raw:
|
| 75 |
+
with user_lock(user_id):
|
| 76 |
+
fixed = _normalize_vfs_tree(vfs_get_tree(user_id))
|
| 77 |
+
vfs_set_tree(user_id, fixed)
|
| 78 |
+
migrate_legacy_twin_paths(user_id, fixed)
|
| 79 |
+
return fixed
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def file_paths(tree: list) -> list[str]:
|
| 83 |
+
return [p.replace("\\", "/") for p in flatten_file_paths(tree)]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _folder_paths(tree: list) -> set[str]:
|
| 87 |
+
out: set[str] = set()
|
| 88 |
+
|
| 89 |
+
def rec(nodes: list) -> None:
|
| 90 |
+
for n in nodes:
|
| 91 |
+
if n.get("type") == "folder":
|
| 92 |
+
out.add(normalize_relative_path(n.get("path") or ""))
|
| 93 |
+
rec(n.get("children") or [])
|
| 94 |
+
|
| 95 |
+
rec(tree)
|
| 96 |
+
return out
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def vfs_entry_kind(tree: list, target_path: str) -> str | None:
|
| 100 |
+
"""Return 'file', 'folder', or None if path is not in the virtual tree."""
|
| 101 |
+
tp = strip_storage_path(target_path)
|
| 102 |
+
if not tp:
|
| 103 |
+
return None
|
| 104 |
+
if tp in set(file_paths(tree)):
|
| 105 |
+
return "file"
|
| 106 |
+
return "folder" if tp in _folder_paths(tree) else None
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def path_exists_in_vfs(tree: list, rel: str) -> bool:
|
| 110 |
+
return vfs_entry_kind(tree, rel) is not None
|
backend/preferences.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-student preferences (reminder emails, answer language), kept in the user's record."""
|
| 2 |
+
import threading
|
| 3 |
+
import time
|
| 4 |
+
|
| 5 |
+
from backend import mailer
|
| 6 |
+
from backend.chroma_store import user_get_by_id, user_update_metadata
|
| 7 |
+
from backend.settings import ANSWER_LANGUAGES, REMINDERS_ENABLED
|
| 8 |
+
|
| 9 |
+
_CACHE_SECONDS = 60
|
| 10 |
+
_cache: dict[str, tuple[float, dict]] = {}
|
| 11 |
+
_lock = threading.Lock()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _from_meta(meta: dict) -> dict:
|
| 15 |
+
language = meta.get("pref_language") or "English"
|
| 16 |
+
return {
|
| 17 |
+
"reminders": bool(int(meta.get("pref_reminders") or 0)),
|
| 18 |
+
"answer_language": language if language in ANSWER_LANGUAGES else "English",
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def reminders_available() -> bool:
|
| 23 |
+
return REMINDERS_ENABLED and mailer.is_configured()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def get(user_id: str) -> dict:
|
| 27 |
+
now = time.time()
|
| 28 |
+
with _lock:
|
| 29 |
+
hit = _cache.get(user_id)
|
| 30 |
+
if hit and now - hit[0] < _CACHE_SECONDS:
|
| 31 |
+
return dict(hit[1])
|
| 32 |
+
user = user_get_by_id(user_id)
|
| 33 |
+
prefs = _from_meta((user or {}).get("meta") or {})
|
| 34 |
+
with _lock:
|
| 35 |
+
_cache[user_id] = (now, prefs)
|
| 36 |
+
return dict(prefs)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def answer_language(user_id: str) -> str:
|
| 40 |
+
try:
|
| 41 |
+
return get(user_id)["answer_language"]
|
| 42 |
+
except Exception:
|
| 43 |
+
return "English"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def language_kwargs(user_id: str) -> dict:
|
| 47 |
+
"""{"language": ...} for AI calls when the student chose a language other than English, else {}."""
|
| 48 |
+
language = answer_language(user_id)
|
| 49 |
+
return {"language": language} if language != "English" else {}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def update(user_id: str, reminders: bool | None = None, answer_language: str | None = None) -> dict:
|
| 53 |
+
fields = {}
|
| 54 |
+
if reminders is not None:
|
| 55 |
+
fields["pref_reminders"] = int(bool(reminders))
|
| 56 |
+
if answer_language is not None:
|
| 57 |
+
if answer_language not in ANSWER_LANGUAGES:
|
| 58 |
+
raise ValueError(f"Answer language must be one of: {', '.join(ANSWER_LANGUAGES)}.")
|
| 59 |
+
fields["pref_language"] = answer_language
|
| 60 |
+
meta = user_update_metadata(user_id, **fields) if fields else (user_get_by_id(user_id) or {}).get("meta", {})
|
| 61 |
+
prefs = _from_meta(meta)
|
| 62 |
+
with _lock:
|
| 63 |
+
_cache[user_id] = (time.time(), prefs)
|
| 64 |
+
return dict(prefs)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def public(user_id: str) -> dict:
|
| 68 |
+
return {**get(user_id), "languages": list(ANSWER_LANGUAGES), "reminders_available": reminders_available()}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def forget(user_id: str) -> None:
|
| 72 |
+
with _lock:
|
| 73 |
+
_cache.pop(user_id, None)
|
backend/rate_limit.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
In-memory request limits (per server process).
|
| 3 |
+
|
| 4 |
+
Three layers use this module:
|
| 5 |
+
- an overall cap on every request per network address and per signed-in browser (api.py middleware),
|
| 6 |
+
- per-route limits on expensive or sensitive routes (logins, uploads, questions, edits, ...),
|
| 7 |
+
- daily caps on paid AI use per user, so one account can't run up the AI bill.
|
| 8 |
+
|
| 9 |
+
Counters live in memory: they reset when the server restarts and aren't shared between processes.
|
| 10 |
+
"""
|
| 11 |
+
import math
|
| 12 |
+
import os
|
| 13 |
+
import threading
|
| 14 |
+
import time
|
| 15 |
+
from collections import deque
|
| 16 |
+
|
| 17 |
+
from fastapi import HTTPException, Request
|
| 18 |
+
|
| 19 |
+
# Scales every limit at once without a code change, e.g. 2 for a busy campus or 0.5 to tighten.
|
| 20 |
+
MULTIPLIER = float((os.getenv("RATE_LIMIT_MULTIPLIER") or "1").strip() or "1")
|
| 21 |
+
|
| 22 |
+
_lock = threading.Lock()
|
| 23 |
+
_hits: dict[str, deque] = {}
|
| 24 |
+
_windows: dict[str, int] = {}
|
| 25 |
+
_MAX_KEYS = 20000
|
| 26 |
+
|
| 27 |
+
# (bucket, key, max requests, window seconds, quota name or None)
|
| 28 |
+
Rule = tuple
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def client_ip(request: Request) -> str:
|
| 32 |
+
"""Best-effort client address (first X-Forwarded-For entry when behind a proxy)."""
|
| 33 |
+
fwd = (request.headers.get("x-forwarded-for") or "").split(",")[0].strip()
|
| 34 |
+
if fwd:
|
| 35 |
+
return fwd
|
| 36 |
+
return request.client.host if request.client else "unknown"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _human_wait(seconds: int) -> str:
|
| 40 |
+
if seconds < 90:
|
| 41 |
+
return f"{seconds} seconds"
|
| 42 |
+
if seconds < 90 * 60:
|
| 43 |
+
return f"{math.ceil(seconds / 60)} minutes"
|
| 44 |
+
return f"{math.ceil(seconds / 3600)} hours"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _prune_locked(now: float) -> None:
|
| 48 |
+
"""Forget counters with no requests inside their own window (keeps daily counters for a day)."""
|
| 49 |
+
stale = [k for k, q in _hits.items() if not q or q[-1] <= now - _windows.get(k, 0)]
|
| 50 |
+
for k in stale:
|
| 51 |
+
_hits.pop(k, None)
|
| 52 |
+
_windows.pop(k, None)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def check_all(rules: list[Rule]) -> None:
|
| 56 |
+
"""
|
| 57 |
+
Check every rule, and record the request against all of them only if none is over its limit,
|
| 58 |
+
so a refused request never uses up another limit. Raises HTTP 429 with a Retry-After header.
|
| 59 |
+
"""
|
| 60 |
+
now = time.monotonic()
|
| 61 |
+
with _lock:
|
| 62 |
+
if len(_hits) > _MAX_KEYS:
|
| 63 |
+
_prune_locked(now)
|
| 64 |
+
queues = []
|
| 65 |
+
for bucket, key, limit, window, quota_name in rules:
|
| 66 |
+
limit = max(1, round(limit * MULTIPLIER))
|
| 67 |
+
k = f"{bucket}:{key}"
|
| 68 |
+
q = _hits.setdefault(k, deque())
|
| 69 |
+
_windows[k] = max(_windows.get(k, 0), int(window))
|
| 70 |
+
while q and q[0] <= now - window:
|
| 71 |
+
q.popleft()
|
| 72 |
+
if len(q) >= limit:
|
| 73 |
+
retry = int(q[0] + window - now) + 1
|
| 74 |
+
wait = _human_wait(retry)
|
| 75 |
+
if quota_name:
|
| 76 |
+
detail = f"You've reached the daily limit of {limit} {quota_name}. You can continue in {wait}."
|
| 77 |
+
else:
|
| 78 |
+
detail = f"Too many requests. Please try again in {wait}."
|
| 79 |
+
raise HTTPException(status_code=429, detail=detail, headers={"Retry-After": str(retry)})
|
| 80 |
+
queues.append(q)
|
| 81 |
+
for q in queues:
|
| 82 |
+
q.append(now)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def check(bucket: str, key: str, limit: int, window_seconds: int, quota_name: str | None = None) -> None:
|
| 86 |
+
"""Record one request for (bucket, key); raise HTTP 429 when over `limit` per window."""
|
| 87 |
+
check_all([(bucket, key, limit, window_seconds, quota_name)])
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def per_user(user_id: str, *rules: tuple) -> None:
|
| 91 |
+
"""Shorthand for several limits on one user: per_user(uid, ("upload", LIMIT, None), ...)."""
|
| 92 |
+
check_all([(bucket, user_id, limit, window, quota) for bucket, (limit, window), quota in rules])
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def reset() -> None:
|
| 96 |
+
"""Forget all counters (used by tests)."""
|
| 97 |
+
with _lock:
|
| 98 |
+
_hits.clear()
|
| 99 |
+
_windows.clear()
|
backend/reminders.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Daily "cards due" reminder emails for students who turned them on (Account settings).
|
| 3 |
+
|
| 4 |
+
A background thread checks every 10 minutes; once the local time (APP_TIMEZONE) is past
|
| 5 |
+
REMINDER_HOUR it emails each opted-in student who has flashcards due, at most once per day.
|
| 6 |
+
Requires SMTP (see mailer.py). Runs in the single server process.
|
| 7 |
+
"""
|
| 8 |
+
import datetime as dt
|
| 9 |
+
import logging
|
| 10 |
+
import threading
|
| 11 |
+
import time
|
| 12 |
+
|
| 13 |
+
from backend import alerts, mailer, settings, study_store, usage
|
| 14 |
+
from backend.chroma_store import user_update_metadata, users_where
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
CHECK_EVERY_SECONDS = 600
|
| 19 |
+
_started = False
|
| 20 |
+
_start_lock = threading.Lock()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _end_of_day(day: dt.date) -> int:
|
| 24 |
+
return int(dt.datetime.combine(day + dt.timedelta(days=1), dt.time(), tzinfo=usage.tz()).timestamp())
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def reminder_text(name: str, due: int) -> str:
|
| 28 |
+
cards = "1 flashcard is" if due == 1 else f"{due} flashcards are"
|
| 29 |
+
return (
|
| 30 |
+
f"Hi {name or 'there'},\n\n"
|
| 31 |
+
f"{cards} due for review today in NoteScanner. A few minutes now saves a lot of re-reading later.\n\n"
|
| 32 |
+
f"Open NoteScanner: {settings.FRONTEND_URL}\n\n"
|
| 33 |
+
"You get this email because daily reminders are on. You can turn them off in Account settings."
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def send_due_reminders(now: float | None = None) -> int:
|
| 38 |
+
"""Send today's reminders (if it's past the reminder hour). Returns how many were sent."""
|
| 39 |
+
if not (settings.REMINDERS_ENABLED and mailer.is_configured()):
|
| 40 |
+
return 0
|
| 41 |
+
now = time.time() if now is None else now
|
| 42 |
+
local = dt.datetime.fromtimestamp(now, usage.tz())
|
| 43 |
+
if local.hour < settings.REMINDER_HOUR:
|
| 44 |
+
return 0
|
| 45 |
+
today = local.date().isoformat()
|
| 46 |
+
sent = 0
|
| 47 |
+
for user in users_where({"pref_reminders": 1}):
|
| 48 |
+
meta = user["meta"]
|
| 49 |
+
if meta.get("reminder_sent_day") == today or not user.get("email"):
|
| 50 |
+
continue
|
| 51 |
+
try:
|
| 52 |
+
due = study_store.due_count(user["user_id"], until=_end_of_day(local.date()))
|
| 53 |
+
if due > 0:
|
| 54 |
+
mailer.send_email(user["email"], f"{due} flashcards to review today", reminder_text(user.get("name"), due))
|
| 55 |
+
sent += 1
|
| 56 |
+
# Mark the day as handled either way, so each student is checked once per day.
|
| 57 |
+
user_update_metadata(user["user_id"], reminder_sent_day=today)
|
| 58 |
+
except Exception as e:
|
| 59 |
+
logger.exception("Reminder for %s failed", user["user_id"])
|
| 60 |
+
alerts.notify("reminder-failed", f"Reminder email failed: {type(e).__name__}: {e}")
|
| 61 |
+
return sent
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _loop() -> None:
|
| 65 |
+
while True:
|
| 66 |
+
try:
|
| 67 |
+
n = send_due_reminders()
|
| 68 |
+
if n:
|
| 69 |
+
logger.info("Sent %d review reminders", n)
|
| 70 |
+
except Exception:
|
| 71 |
+
logger.exception("Reminder check failed")
|
| 72 |
+
time.sleep(CHECK_EVERY_SECONDS)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def start() -> None:
|
| 76 |
+
"""Start the reminder thread once (no-op when reminders or email aren't set up)."""
|
| 77 |
+
global _started
|
| 78 |
+
with _start_lock:
|
| 79 |
+
if _started or not (settings.REMINDERS_ENABLED and mailer.is_configured()):
|
| 80 |
+
return
|
| 81 |
+
_started = True
|
| 82 |
+
threading.Thread(target=_loop, name="reminders", daemon=True).start()
|
backend/routes/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""HTTP routes, one module per feature area."""
|
backend/routes/account.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sign-up, sign-in, sign-out, password changes/resets and account deletion."""
|
| 2 |
+
import logging
|
| 3 |
+
import re
|
| 4 |
+
import secrets
|
| 5 |
+
import time
|
| 6 |
+
import uuid
|
| 7 |
+
|
| 8 |
+
import httpx
|
| 9 |
+
from fastapi import APIRouter, Form, Request
|
| 10 |
+
from fastapi.responses import JSONResponse
|
| 11 |
+
|
| 12 |
+
from backend import (
|
| 13 |
+
chat_cache,
|
| 14 |
+
feedback,
|
| 15 |
+
legacy_migration,
|
| 16 |
+
mailer,
|
| 17 |
+
preferences,
|
| 18 |
+
rate_limit,
|
| 19 |
+
settings,
|
| 20 |
+
starter_notes,
|
| 21 |
+
study_store,
|
| 22 |
+
uploads,
|
| 23 |
+
usage,
|
| 24 |
+
)
|
| 25 |
+
from backend.auth import (
|
| 26 |
+
SESSION_HEADER,
|
| 27 |
+
create_session,
|
| 28 |
+
end_session,
|
| 29 |
+
get_user_id_from_session,
|
| 30 |
+
hash_password,
|
| 31 |
+
verify_password,
|
| 32 |
+
)
|
| 33 |
+
from backend.chroma_store import (
|
| 34 |
+
delete_user_notes_collection,
|
| 35 |
+
delete_user_vfs_collection,
|
| 36 |
+
onenote_token_delete,
|
| 37 |
+
password_reset_create,
|
| 38 |
+
password_reset_delete_for_user,
|
| 39 |
+
password_reset_pop_user_id,
|
| 40 |
+
session_delete_all_for_user,
|
| 41 |
+
user_create,
|
| 42 |
+
user_delete,
|
| 43 |
+
user_document_delete_many,
|
| 44 |
+
user_exists_by_email,
|
| 45 |
+
user_get_by_email,
|
| 46 |
+
user_get_by_id,
|
| 47 |
+
user_update_password,
|
| 48 |
+
)
|
| 49 |
+
from backend.deps import SignedInUser
|
| 50 |
+
from backend.rate_limit import client_ip
|
| 51 |
+
from backend.settings import (
|
| 52 |
+
FRONTEND_URL,
|
| 53 |
+
LIMIT_FORGOT_PER_EMAIL,
|
| 54 |
+
LIMIT_FORGOT_PER_IP,
|
| 55 |
+
LIMIT_GUEST_ID_PER_IP,
|
| 56 |
+
LIMIT_LOGIN_PER_EMAIL,
|
| 57 |
+
LIMIT_LOGIN_PER_IP,
|
| 58 |
+
LIMIT_PASSWORD_CHECK_PER_USER,
|
| 59 |
+
LIMIT_REGISTER_PER_IP,
|
| 60 |
+
LIMIT_RESET_PER_IP,
|
| 61 |
+
MAX_PASSWORD_BYTES,
|
| 62 |
+
MIN_PASSWORD_LEN,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
logger = logging.getLogger(__name__)
|
| 66 |
+
router = APIRouter()
|
| 67 |
+
|
| 68 |
+
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _error(message: str, status_code: int = 400) -> JSONResponse:
|
| 72 |
+
return JSONResponse({"error": message}, status_code=status_code)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _password_problem(password: str) -> str | None:
|
| 76 |
+
if len(password) < MIN_PASSWORD_LEN:
|
| 77 |
+
return f"Password must be at least {MIN_PASSWORD_LEN} characters."
|
| 78 |
+
if len(password.encode("utf-8")) > MAX_PASSWORD_BYTES:
|
| 79 |
+
return "Password is too long (maximum 72 characters)."
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _database_error(action: str, e: Exception) -> JSONResponse:
|
| 84 |
+
"""Log the real cause; tell the user whether the database is down or something else failed."""
|
| 85 |
+
logger.exception("%s failed", action)
|
| 86 |
+
if isinstance(e, (ConnectionError, TimeoutError, httpx.TransportError)) or "connect" in str(e).lower():
|
| 87 |
+
return _error("Can't reach the database right now. Please try again in a moment.", 503)
|
| 88 |
+
return _error(f"{action} failed because of a server error. Please try again.", 500)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _check_password(user_id: str, password: str) -> bool:
|
| 92 |
+
user = user_get_by_id(user_id, with_password=True)
|
| 93 |
+
return bool(user and user.get("hashed_password") and verify_password(password, user["hashed_password"]))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@router.post("/register")
|
| 97 |
+
def register(
|
| 98 |
+
request: Request,
|
| 99 |
+
email: str = Form(...),
|
| 100 |
+
password: str = Form(...),
|
| 101 |
+
name: str = Form(""),
|
| 102 |
+
accepted_privacy: str = Form(""),
|
| 103 |
+
app_name: str = Form(""),
|
| 104 |
+
):
|
| 105 |
+
rate_limit.check("register", client_ip(request), *LIMIT_REGISTER_PER_IP)
|
| 106 |
+
if accepted_privacy.strip().lower() not in ("1", "true", "yes", "on"):
|
| 107 |
+
return _error("Please read and accept the privacy note.")
|
| 108 |
+
email = (email or "").strip().lower()
|
| 109 |
+
name = (name or "").strip()[:80]
|
| 110 |
+
if len(email) > 254 or not _EMAIL_RE.match(email):
|
| 111 |
+
return _error("Please enter a valid email address.")
|
| 112 |
+
problem = _password_problem(password)
|
| 113 |
+
if problem:
|
| 114 |
+
return _error(problem)
|
| 115 |
+
try:
|
| 116 |
+
if user_exists_by_email(email):
|
| 117 |
+
return _error("Email already registered.")
|
| 118 |
+
display_name = name or email.split("@")[0]
|
| 119 |
+
user_id = user_create(
|
| 120 |
+
email,
|
| 121 |
+
hash_password(password),
|
| 122 |
+
display_name,
|
| 123 |
+
privacy_accepted_at=int(time.time()),
|
| 124 |
+
privacy_version=settings.PRIVACY_VERSION,
|
| 125 |
+
)
|
| 126 |
+
session_id = create_session(user_id)
|
| 127 |
+
if settings.STARTER_NOTES:
|
| 128 |
+
starter_notes.add_starter_notes_in_background(user_id, (app_name or "").strip())
|
| 129 |
+
return JSONResponse({"session_id": session_id, "user_id": user_id, "name": display_name})
|
| 130 |
+
except Exception as e:
|
| 131 |
+
return _database_error("Sign-up", e)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@router.post("/login")
|
| 135 |
+
def login(request: Request, email: str = Form(...), password: str = Form(...)):
|
| 136 |
+
ip = client_ip(request)
|
| 137 |
+
email = (email or "").strip().lower()
|
| 138 |
+
rate_limit.check("login-ip", ip, *LIMIT_LOGIN_PER_IP)
|
| 139 |
+
rate_limit.check("login", f"{ip}|{email}", *LIMIT_LOGIN_PER_EMAIL)
|
| 140 |
+
try:
|
| 141 |
+
user = user_get_by_email(email)
|
| 142 |
+
if not user or not verify_password(password, user["hashed_password"]):
|
| 143 |
+
return _error("Invalid email or password.", 401)
|
| 144 |
+
user_id = user["user_id"]
|
| 145 |
+
session_id = create_session(user_id)
|
| 146 |
+
name = user.get("name") or (user.get("email") or "").split("@")[0]
|
| 147 |
+
return JSONResponse({"session_id": session_id, "user_id": user_id, "name": name})
|
| 148 |
+
except Exception as e:
|
| 149 |
+
return _database_error("Sign-in", e)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@router.post("/logout")
|
| 153 |
+
def logout(request: Request):
|
| 154 |
+
"""End the session on the server so the session id stops working everywhere."""
|
| 155 |
+
end_session(request.headers.get(SESSION_HEADER))
|
| 156 |
+
return JSONResponse({"message": "Signed out."})
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@router.get("/me")
|
| 160 |
+
def get_me(request: Request):
|
| 161 |
+
"""Return current user info (name) for the session. Requires valid X-Session-Id."""
|
| 162 |
+
user_id = get_user_id_from_session(request.headers.get(SESSION_HEADER))
|
| 163 |
+
if not user_id:
|
| 164 |
+
return _error("Not signed in.", 401)
|
| 165 |
+
user = user_get_by_id(user_id)
|
| 166 |
+
if not user:
|
| 167 |
+
return _error("User not found.", 404)
|
| 168 |
+
name = user.get("name") or (user.get("email") or "").split("@")[0]
|
| 169 |
+
return JSONResponse({
|
| 170 |
+
"name": name or "User",
|
| 171 |
+
"user_id": user_id,
|
| 172 |
+
"email": user.get("email") or "",
|
| 173 |
+
"is_admin": (user.get("email") or "").lower() in settings.ADMIN_EMAILS,
|
| 174 |
+
"preferences": preferences.get(user_id),
|
| 175 |
+
})
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@router.get("/account/preferences")
|
| 179 |
+
def get_preferences(user_id: SignedInUser = None):
|
| 180 |
+
return preferences.public(user_id)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
@router.post("/account/preferences")
|
| 184 |
+
def set_preferences(reminders: str = Form(None), answer_language: str = Form(None), user_id: SignedInUser = None):
|
| 185 |
+
try:
|
| 186 |
+
preferences.update(
|
| 187 |
+
user_id,
|
| 188 |
+
reminders=None if reminders is None else reminders.strip().lower() in ("1", "true", "yes", "on"),
|
| 189 |
+
answer_language=answer_language,
|
| 190 |
+
)
|
| 191 |
+
except ValueError as e:
|
| 192 |
+
return _error(str(e))
|
| 193 |
+
return preferences.public(user_id)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
@router.get("/guest_id")
|
| 197 |
+
def get_guest_id(request: Request):
|
| 198 |
+
"""Return a new guest id for anonymous use. Frontend stores it and sends X-Guest-Id header."""
|
| 199 |
+
rate_limit.check("guest-id", client_ip(request), *LIMIT_GUEST_ID_PER_IP)
|
| 200 |
+
return JSONResponse({"guest_id": str(uuid.uuid4())})
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
@router.post("/account/change_password")
|
| 204 |
+
def change_password(
|
| 205 |
+
request: Request,
|
| 206 |
+
current_password: str = Form(...),
|
| 207 |
+
new_password: str = Form(...),
|
| 208 |
+
user_id: SignedInUser = None,
|
| 209 |
+
):
|
| 210 |
+
rate_limit.check("password-check", user_id, *LIMIT_PASSWORD_CHECK_PER_USER)
|
| 211 |
+
if not _check_password(user_id, current_password):
|
| 212 |
+
return _error("Your current password is incorrect.", 400)
|
| 213 |
+
problem = _password_problem(new_password)
|
| 214 |
+
if problem:
|
| 215 |
+
return _error(problem)
|
| 216 |
+
user_update_password(user_id, hash_password(new_password))
|
| 217 |
+
# Sign out every other device; this one stays signed in.
|
| 218 |
+
session_delete_all_for_user(user_id, keep_session_id=request.headers.get(SESSION_HEADER))
|
| 219 |
+
return JSONResponse({"message": "Password changed. Other devices have been signed out."})
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
@router.post("/account/delete")
|
| 223 |
+
def delete_account(password: str = Form(...), user_id: SignedInUser = None):
|
| 224 |
+
"""Permanently delete the account and everything stored for it."""
|
| 225 |
+
rate_limit.check("password-check", user_id, *LIMIT_PASSWORD_CHECK_PER_USER)
|
| 226 |
+
if not _check_password(user_id, password):
|
| 227 |
+
return _error("Password is incorrect.", 400)
|
| 228 |
+
delete_user_notes_collection(user_id)
|
| 229 |
+
delete_user_vfs_collection(user_id)
|
| 230 |
+
study_store.delete_all(user_id)
|
| 231 |
+
user_document_delete_many(user_id, path_filter=None)
|
| 232 |
+
onenote_token_delete(user_id)
|
| 233 |
+
password_reset_delete_for_user(user_id)
|
| 234 |
+
chat_cache.clear_user(user_id)
|
| 235 |
+
uploads.forget_user_jobs(user_id)
|
| 236 |
+
legacy_migration.forget_user(user_id)
|
| 237 |
+
usage.delete_user(user_id)
|
| 238 |
+
feedback.delete_user(user_id)
|
| 239 |
+
preferences.forget(user_id)
|
| 240 |
+
session_delete_all_for_user(user_id)
|
| 241 |
+
user_delete(user_id)
|
| 242 |
+
return JSONResponse({"message": "Your account and all your notes have been deleted."})
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
FORGOT_MESSAGE = "If an account exists for that email, we've sent a link to reset the password. It expires in 1 hour."
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
@router.post("/password/forgot")
|
| 249 |
+
def forgot_password(request: Request, email: str = Form(...)):
|
| 250 |
+
if not mailer.is_configured():
|
| 251 |
+
return _error("Password reset by email isn't set up on this server.", 503)
|
| 252 |
+
email = (email or "").strip().lower()
|
| 253 |
+
rate_limit.check("forgot-ip", client_ip(request), *LIMIT_FORGOT_PER_IP)
|
| 254 |
+
rate_limit.check("forgot", email, *LIMIT_FORGOT_PER_EMAIL)
|
| 255 |
+
user = user_get_by_email(email) if _EMAIL_RE.match(email) else None
|
| 256 |
+
if user:
|
| 257 |
+
token = secrets.token_urlsafe(32)
|
| 258 |
+
password_reset_create(user["user_id"], token)
|
| 259 |
+
link = f"{FRONTEND_URL.rstrip('/')}/?reset_token={token}"
|
| 260 |
+
try:
|
| 261 |
+
mailer.send_password_reset(user["email"], link)
|
| 262 |
+
except Exception:
|
| 263 |
+
logger.exception("Password reset email failed")
|
| 264 |
+
# Same answer either way, so the form can't be used to find out who has an account.
|
| 265 |
+
return JSONResponse({"message": FORGOT_MESSAGE})
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
@router.post("/password/reset")
|
| 269 |
+
def reset_password(request: Request, token: str = Form(...), new_password: str = Form(...)):
|
| 270 |
+
rate_limit.check("reset", client_ip(request), *LIMIT_RESET_PER_IP)
|
| 271 |
+
problem = _password_problem(new_password)
|
| 272 |
+
if problem:
|
| 273 |
+
return _error(problem)
|
| 274 |
+
user_id = password_reset_pop_user_id((token or "").strip())
|
| 275 |
+
if not user_id:
|
| 276 |
+
return _error("This reset link is invalid or has expired. Please ask for a new one.")
|
| 277 |
+
user_update_password(user_id, hash_password(new_password))
|
| 278 |
+
session_delete_all_for_user(user_id)
|
| 279 |
+
return JSONResponse({"message": "Password updated. Please sign in with your new password."})
|
backend/routes/admin.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Student feedback, and the admin page (usage, cost and feedback for running a pilot)."""
|
| 2 |
+
import datetime as dt
|
| 3 |
+
import time
|
| 4 |
+
|
| 5 |
+
from fastapi import APIRouter, Form, HTTPException
|
| 6 |
+
from fastapi.responses import JSONResponse
|
| 7 |
+
|
| 8 |
+
from backend import feedback, rate_limit, settings, usage
|
| 9 |
+
from backend.chroma_store import user_get_by_id
|
| 10 |
+
from backend.deps import SignedInUser
|
| 11 |
+
from backend.library import USAGE_ID as LIBRARY_USAGE_ID
|
| 12 |
+
|
| 13 |
+
router = APIRouter()
|
| 14 |
+
|
| 15 |
+
LIMIT_FEEDBACK_PER_USER = (30, 600)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def is_admin(user_id: str) -> bool:
|
| 19 |
+
if not settings.ADMIN_EMAILS:
|
| 20 |
+
return False
|
| 21 |
+
user = user_get_by_id(user_id)
|
| 22 |
+
return bool(user and (user.get("email") or "").lower() in settings.ADMIN_EMAILS)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _require_admin(user_id: str) -> None:
|
| 26 |
+
if not is_admin(user_id):
|
| 27 |
+
raise HTTPException(status_code=403, detail="Only admins can see this page.")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@router.post("/feedback")
|
| 31 |
+
def send_feedback(
|
| 32 |
+
kind: str = Form("general"),
|
| 33 |
+
rating: str = Form(""),
|
| 34 |
+
comment: str = Form(""),
|
| 35 |
+
question: str = Form(""),
|
| 36 |
+
answer: str = Form(""),
|
| 37 |
+
sources: str = Form(""),
|
| 38 |
+
selection_stage: str = Form(""),
|
| 39 |
+
user_id: SignedInUser = None,
|
| 40 |
+
):
|
| 41 |
+
if kind not in feedback.KINDS or rating not in feedback.RATINGS:
|
| 42 |
+
return JSONResponse({"error": "kind must be answer/general and rating up/down/empty."}, status_code=400)
|
| 43 |
+
if kind == "general" and not comment.strip():
|
| 44 |
+
return JSONResponse({"error": "Please write some feedback first."}, status_code=400)
|
| 45 |
+
rate_limit.check("feedback", user_id, *LIMIT_FEEDBACK_PER_USER)
|
| 46 |
+
feedback.add(user_id, kind, rating, selection_stage, comment=comment, question=question, answer=answer, sources=sources)
|
| 47 |
+
if rating:
|
| 48 |
+
usage.record(user_id, **{f"ratings_{rating}": 1})
|
| 49 |
+
return JSONResponse({"message": "Thanks for the feedback!"}, status_code=201)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@router.get("/admin/stats")
|
| 53 |
+
def admin_stats(days: int = 7, user_id: SignedInUser = None):
|
| 54 |
+
_require_admin(user_id)
|
| 55 |
+
days = max(1, min(int(days), 90))
|
| 56 |
+
today = usage.today()
|
| 57 |
+
start = today - dt.timedelta(days=days - 1)
|
| 58 |
+
records = usage.records_since(start)
|
| 59 |
+
|
| 60 |
+
totals = {k: 0 for k in usage.COUNTERS}
|
| 61 |
+
daily: dict[str, dict] = {}
|
| 62 |
+
for i in range(days):
|
| 63 |
+
d = (start + dt.timedelta(days=i)).isoformat()
|
| 64 |
+
daily[d] = {"day": d, "active_users": 0, "questions": 0, "uploads": 0, "reviews": 0, "study_requests": 0}
|
| 65 |
+
active: set[str] = set()
|
| 66 |
+
for r in records:
|
| 67 |
+
for k in usage.COUNTERS:
|
| 68 |
+
totals[k] += int(r.get(k) or 0)
|
| 69 |
+
if r.get("user_id") == LIBRARY_USAGE_ID:
|
| 70 |
+
continue # pages the shared library sent to OCR: counted in the totals, not a student
|
| 71 |
+
row = daily.get(r.get("day"))
|
| 72 |
+
if row is not None:
|
| 73 |
+
row["active_users"] += 1
|
| 74 |
+
for k in ("questions", "uploads", "reviews", "study_requests"):
|
| 75 |
+
row[k] += int(r.get(k) or 0)
|
| 76 |
+
active.add(r.get("user_id"))
|
| 77 |
+
|
| 78 |
+
rated = totals["ratings_up"] + totals["ratings_down"]
|
| 79 |
+
prices = usage.prices_set()
|
| 80 |
+
return {
|
| 81 |
+
"days": days,
|
| 82 |
+
"totals": {
|
| 83 |
+
"active_users": len(active),
|
| 84 |
+
**{k: totals[k] for k in ("questions", "uploads", "pages_read", "upload_failures", "study_requests",
|
| 85 |
+
"reviews", "ratings_up", "ratings_down", "prompt_tokens", "completion_tokens")},
|
| 86 |
+
"helpful_share": round(totals["ratings_up"] / rated, 3) if rated else None,
|
| 87 |
+
"estimated_cost": round(usage.cost_of(totals), 2) if prices else None,
|
| 88 |
+
},
|
| 89 |
+
"daily": list(daily.values()),
|
| 90 |
+
"budget": {
|
| 91 |
+
"monthly_budget": settings.AI_MONTHLY_BUDGET or None,
|
| 92 |
+
"month_cost": round(usage.month_cost(), 2) if prices else None,
|
| 93 |
+
"currency": settings.AI_PRICE_CURRENCY,
|
| 94 |
+
},
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@router.get("/admin/feedback")
|
| 99 |
+
def admin_feedback(limit: int = 50, user_id: SignedInUser = None):
|
| 100 |
+
_require_admin(user_id)
|
| 101 |
+
rows = feedback.recent(limit=max(1, min(int(limit), 200)), since=int(time.time()) - 90 * 86400)
|
| 102 |
+
emails: dict[str, str] = {}
|
| 103 |
+
for r in rows:
|
| 104 |
+
uid = r.pop("user_id", "") or ""
|
| 105 |
+
if uid not in emails:
|
| 106 |
+
user = user_get_by_id(uid) if uid else None
|
| 107 |
+
emails[uid] = (user or {}).get("email") or "(deleted account)"
|
| 108 |
+
r["user_email"] = emails[uid]
|
| 109 |
+
return {"feedback": rows}
|
backend/routes/chat.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Chat: temporary chat uploads (+ button) and answering questions from notes."""
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from fastapi import APIRouter, File, Form, HTTPException, UploadFile
|
| 8 |
+
from fastapi.responses import JSONResponse, StreamingResponse
|
| 9 |
+
|
| 10 |
+
from backend import alerts, chat_cache, library, llm_pipeline, preferences, rate_limit, uploads, usage
|
| 11 |
+
from backend.deps import SignedInUser
|
| 12 |
+
from backend.ingest_api import embed_texts
|
| 13 |
+
from backend.paths import file_paths, get_vfs_tree_clean, strip_storage_path
|
| 14 |
+
from backend.search import SearchResult, course_of, find_context
|
| 15 |
+
from backend.settings import (
|
| 16 |
+
LIMIT_QUESTIONS_PER_DAY,
|
| 17 |
+
LIMIT_QUESTIONS_PER_USER,
|
| 18 |
+
LIMIT_UPLOADS_PER_DAY,
|
| 19 |
+
LIMIT_UPLOADS_PER_USER,
|
| 20 |
+
MAX_CHAT_FILES_PER_SESSION,
|
| 21 |
+
MAX_CHAT_UPLOAD_CHARS,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
logger = logging.getLogger(__name__)
|
| 25 |
+
router = APIRouter()
|
| 26 |
+
|
| 27 |
+
AI_UNAVAILABLE = "The AI couldn't answer right now. Please try again."
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _split_text(t: str, size: int = 900, overlap: int = 140) -> list[str]:
|
| 31 |
+
tx = (t or "").strip()
|
| 32 |
+
if not tx:
|
| 33 |
+
return []
|
| 34 |
+
out: list[str] = []
|
| 35 |
+
i = 0
|
| 36 |
+
n = len(tx)
|
| 37 |
+
while i < n:
|
| 38 |
+
out.append(tx[i : i + size])
|
| 39 |
+
i += max(1, size - overlap)
|
| 40 |
+
return out
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@router.post("/chat/upload_ephemeral")
|
| 44 |
+
def chat_upload_ephemeral(chat_session_id: str = Form(...), file: UploadFile = File(...), user_id: SignedInUser = None):
|
| 45 |
+
rate_limit.per_user(
|
| 46 |
+
user_id,
|
| 47 |
+
("upload", LIMIT_UPLOADS_PER_USER, None),
|
| 48 |
+
("upload-day", LIMIT_UPLOADS_PER_DAY, "uploads"),
|
| 49 |
+
)
|
| 50 |
+
sid = (chat_session_id or "").strip()
|
| 51 |
+
if not sid:
|
| 52 |
+
return JSONResponse({"error": "chat_session_id is required."}, status_code=400)
|
| 53 |
+
if chat_cache.count(user_id, sid) >= MAX_CHAT_FILES_PER_SESSION:
|
| 54 |
+
return JSONResponse(
|
| 55 |
+
{"error": f"This chat already has {MAX_CHAT_FILES_PER_SESSION} files. Start a new chat to add more."},
|
| 56 |
+
status_code=400,
|
| 57 |
+
)
|
| 58 |
+
raw_name = uploads.clean_upload_name(file)
|
| 59 |
+
uploads.check_supported_type(raw_name)
|
| 60 |
+
usage.check_budget()
|
| 61 |
+
data = uploads.read_upload(file)
|
| 62 |
+
extracted = uploads.extract_text_or_http_error(raw_name, data)
|
| 63 |
+
usage.record(user_id, uploads=1, pages_read=extracted.pages_sent_to_ai)
|
| 64 |
+
text, source = extracted.text, extracted.note
|
| 65 |
+
|
| 66 |
+
truncated = len(text) > MAX_CHAT_UPLOAD_CHARS
|
| 67 |
+
text = text[:MAX_CHAT_UPLOAD_CHARS]
|
| 68 |
+
# Embed every chunk once now, so questions search the whole file instead of only its start.
|
| 69 |
+
chunks = _split_text(text)
|
| 70 |
+
embeddings = np.asarray(embed_texts(chunks), dtype=np.float32)
|
| 71 |
+
count = chat_cache.add(
|
| 72 |
+
user_id,
|
| 73 |
+
sid,
|
| 74 |
+
{
|
| 75 |
+
"name": raw_name,
|
| 76 |
+
"chunks": chunks,
|
| 77 |
+
"embeddings": embeddings,
|
| 78 |
+
"source": source,
|
| 79 |
+
"uploaded_at": datetime.now().isoformat(),
|
| 80 |
+
},
|
| 81 |
+
)
|
| 82 |
+
return JSONResponse(
|
| 83 |
+
{
|
| 84 |
+
"message": f"Cached '{raw_name}' for this chat session.",
|
| 85 |
+
"chat_session_id": sid,
|
| 86 |
+
"cached_files_count": count,
|
| 87 |
+
"text_chars": len(text),
|
| 88 |
+
"text_truncated": truncated,
|
| 89 |
+
"extractor_note": source,
|
| 90 |
+
}
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@router.post("/chat/session/clear")
|
| 95 |
+
def clear_chat_session_cache(chat_session_id: str = Form(...), user_id: SignedInUser = None):
|
| 96 |
+
sid = (chat_session_id or "").strip()
|
| 97 |
+
if not sid:
|
| 98 |
+
return JSONResponse({"error": "chat_session_id is required."}, status_code=400)
|
| 99 |
+
deleted = chat_cache.clear(user_id, sid)
|
| 100 |
+
return JSONResponse({"message": "Chat cache cleared.", "deleted_files": deleted})
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _ai_failed(err: str) -> None:
|
| 104 |
+
logger.warning("Answer generation failed: %s", err)
|
| 105 |
+
alerts.notify("ai-unavailable", f"Sarvam chat failed: {err}")
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _prepare_question(
|
| 109 |
+
user_id: str,
|
| 110 |
+
query: str,
|
| 111 |
+
highlight: str,
|
| 112 |
+
opened_file_path: str,
|
| 113 |
+
course_path: str,
|
| 114 |
+
include_course_context: bool,
|
| 115 |
+
chat_session_id: str,
|
| 116 |
+
library_path: str = "",
|
| 117 |
+
) -> tuple[str, str, str, list[dict], SearchResult]:
|
| 118 |
+
"""Validate the question and find the note excerpts to answer it from (HTTP errors raise)."""
|
| 119 |
+
q = (query or "").strip()
|
| 120 |
+
if not q:
|
| 121 |
+
raise HTTPException(status_code=400, detail="Query is empty.")
|
| 122 |
+
rate_limit.per_user(
|
| 123 |
+
user_id,
|
| 124 |
+
("query", LIMIT_QUESTIONS_PER_USER, None),
|
| 125 |
+
("query-day", LIMIT_QUESTIONS_PER_DAY, "questions"),
|
| 126 |
+
)
|
| 127 |
+
usage.check_budget()
|
| 128 |
+
all_paths = file_paths(get_vfs_tree_clean(user_id))
|
| 129 |
+
opened = strip_storage_path(opened_file_path or "")
|
| 130 |
+
course = course_of(opened, strip_storage_path(course_path or ""))
|
| 131 |
+
ephemeral = chat_cache.items(user_id, chat_session_id)
|
| 132 |
+
hl = (highlight or "").strip()
|
| 133 |
+
full_q = f'Regarding this selection:\n"""{hl}"""\n\n{q}' if hl else q
|
| 134 |
+
result = find_context(
|
| 135 |
+
user_id, full_q, all_paths, opened, course, ephemeral, include_course_context, library_path=library_path
|
| 136 |
+
)
|
| 137 |
+
if not result.selected:
|
| 138 |
+
raise HTTPException(
|
| 139 |
+
status_code=400,
|
| 140 |
+
detail=library.NOT_READY
|
| 141 |
+
if library.scope_of(library_path)[1]
|
| 142 |
+
else "No notes found to answer from. Upload notes, open a file, or attach one with +.",
|
| 143 |
+
)
|
| 144 |
+
usage.record(user_id, questions=1)
|
| 145 |
+
return q, full_q, opened, ephemeral, result
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _answer_metadata(q: str, opened: str, ephemeral: list[dict], result: SearchResult) -> dict:
|
| 149 |
+
return {
|
| 150 |
+
"query": q,
|
| 151 |
+
"source_documents": result.source_documents(),
|
| 152 |
+
"grounded_on_path": opened,
|
| 153 |
+
"ephemeral_files_used": len(ephemeral),
|
| 154 |
+
"selection_stage": result.stage,
|
| 155 |
+
"score_ephemeral_best": result.best_scores.get("ephemeral", -1.0),
|
| 156 |
+
"score_library_file_best": result.best_scores.get("library_file", -1.0),
|
| 157 |
+
"score_library_subject_best": result.best_scores.get("library_subject", -1.0),
|
| 158 |
+
"score_opened_best": result.best_scores.get("opened", -1.0),
|
| 159 |
+
"score_course_best": result.best_scores.get("course", -1.0),
|
| 160 |
+
"score_all_notes_best": result.best_scores.get("all_notes", -1.0),
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@router.post("/query_folder")
|
| 165 |
+
def query_notes(
|
| 166 |
+
query: str = Form(...),
|
| 167 |
+
highlight: str = Form(""),
|
| 168 |
+
opened_file_path: str = Form(""),
|
| 169 |
+
course_path: str = Form(""),
|
| 170 |
+
include_course_context: bool = Form(True),
|
| 171 |
+
chat_session_id: str = Form(""),
|
| 172 |
+
library_path: str = Form(""),
|
| 173 |
+
user_id: SignedInUser = None,
|
| 174 |
+
):
|
| 175 |
+
q, full_q, opened, ephemeral, result = _prepare_question(
|
| 176 |
+
user_id, query, highlight, opened_file_path, course_path, include_course_context, chat_session_id, library_path
|
| 177 |
+
)
|
| 178 |
+
llm_pipeline.take_usage()
|
| 179 |
+
answer, err = llm_pipeline.sarvam_rag_answer(full_q, result.context(), **preferences.language_kwargs(user_id))
|
| 180 |
+
usage.record(user_id, **llm_pipeline.take_usage())
|
| 181 |
+
if err:
|
| 182 |
+
_ai_failed(err)
|
| 183 |
+
return JSONResponse({"error": AI_UNAVAILABLE, "query": q, "answer": "", "source_documents": []}, status_code=503)
|
| 184 |
+
return JSONResponse({**_answer_metadata(q, opened, ephemeral, result), "answer": answer or ""})
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
@router.post("/query_folder/stream")
|
| 188 |
+
def query_notes_stream(
|
| 189 |
+
query: str = Form(...),
|
| 190 |
+
highlight: str = Form(""),
|
| 191 |
+
opened_file_path: str = Form(""),
|
| 192 |
+
course_path: str = Form(""),
|
| 193 |
+
include_course_context: bool = Form(True),
|
| 194 |
+
chat_session_id: str = Form(""),
|
| 195 |
+
library_path: str = Form(""),
|
| 196 |
+
user_id: SignedInUser = None,
|
| 197 |
+
):
|
| 198 |
+
"""
|
| 199 |
+
Same as /query_folder, but the answer arrives as it's written. Newline-delimited JSON:
|
| 200 |
+
{"type":"meta",...sources} then {"type":"delta","text":...}* then {"type":"done"} or {"type":"error"}.
|
| 201 |
+
`library_path` asks about a shared course PDF (see library.py) instead of an uploaded file.
|
| 202 |
+
"""
|
| 203 |
+
q, full_q, opened, ephemeral, result = _prepare_question(
|
| 204 |
+
user_id, query, highlight, opened_file_path, course_path, include_course_context, chat_session_id, library_path
|
| 205 |
+
)
|
| 206 |
+
context = result.context()
|
| 207 |
+
lang = preferences.language_kwargs(user_id)
|
| 208 |
+
|
| 209 |
+
def lines():
|
| 210 |
+
yield json.dumps({"type": "meta", **_answer_metadata(q, opened, ephemeral, result)}) + "\n"
|
| 211 |
+
written: list[str] = []
|
| 212 |
+
try:
|
| 213 |
+
for piece in llm_pipeline.sarvam_rag_answer_stream(full_q, context, **lang):
|
| 214 |
+
written.append(piece)
|
| 215 |
+
yield json.dumps({"type": "delta", "text": piece}) + "\n"
|
| 216 |
+
except Exception as e:
|
| 217 |
+
_ai_failed(str(e))
|
| 218 |
+
yield json.dumps({"type": "error", "error": AI_UNAVAILABLE}) + "\n"
|
| 219 |
+
return
|
| 220 |
+
finally:
|
| 221 |
+
# Streaming replies don't report tokens; estimate them for the cost figures.
|
| 222 |
+
usage.record(
|
| 223 |
+
user_id,
|
| 224 |
+
prompt_tokens=llm_pipeline.estimate_tokens(full_q + context),
|
| 225 |
+
completion_tokens=llm_pipeline.estimate_tokens("".join(written)) if written else 0,
|
| 226 |
+
)
|
| 227 |
+
if not written:
|
| 228 |
+
_ai_failed("empty streamed answer")
|
| 229 |
+
yield json.dumps({"type": "error", "error": AI_UNAVAILABLE}) + "\n"
|
| 230 |
+
return
|
| 231 |
+
yield json.dumps({"type": "done"}) + "\n"
|
| 232 |
+
|
| 233 |
+
return StreamingResponse(lines(), media_type="application/x-ndjson", headers={"Cache-Control": "no-cache"})
|
backend/routes/files.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Folder tree, uploads, moves/renames/deletes, viewing and editing a file's text, file metadata."""
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
from fastapi import APIRouter, File, Form, UploadFile
|
| 6 |
+
from fastapi.responses import JSONResponse
|
| 7 |
+
|
| 8 |
+
from backend import legacy_migration, rate_limit, uploads, usage
|
| 9 |
+
from backend.chroma_store import (
|
| 10 |
+
delete_user_notes_by_paths,
|
| 11 |
+
delete_user_notes_collection,
|
| 12 |
+
delete_user_vfs_collection,
|
| 13 |
+
user_document_delete_by_path,
|
| 14 |
+
user_document_delete_many,
|
| 15 |
+
user_document_get,
|
| 16 |
+
user_document_rename_path,
|
| 17 |
+
user_document_upsert,
|
| 18 |
+
user_documents_relocate_prefix,
|
| 19 |
+
user_lock,
|
| 20 |
+
user_notes_concat_text_for_path,
|
| 21 |
+
vfs_set_tree,
|
| 22 |
+
)
|
| 23 |
+
from backend.deps import EffectiveUser, SignedInUser
|
| 24 |
+
from backend.file_meta import (
|
| 25 |
+
delete_key,
|
| 26 |
+
delete_keys_for_prefix,
|
| 27 |
+
file_meta_relocate_prefix,
|
| 28 |
+
file_meta_rename_path,
|
| 29 |
+
load_file_meta,
|
| 30 |
+
set_entry,
|
| 31 |
+
)
|
| 32 |
+
from backend.ingest_api import (
|
| 33 |
+
chunks_relocate_files,
|
| 34 |
+
chunks_relocate_path,
|
| 35 |
+
ingest_text_for_path,
|
| 36 |
+
refresh_metadata_for_paths,
|
| 37 |
+
)
|
| 38 |
+
from backend.paths import (
|
| 39 |
+
file_paths,
|
| 40 |
+
get_vfs_tree_clean,
|
| 41 |
+
join_path,
|
| 42 |
+
parent_of,
|
| 43 |
+
path_exists_in_vfs,
|
| 44 |
+
strip_storage_path,
|
| 45 |
+
valid_name,
|
| 46 |
+
vfs_entry_kind,
|
| 47 |
+
)
|
| 48 |
+
from backend.settings import (
|
| 49 |
+
LIMIT_DELETE_ALL_PER_USER,
|
| 50 |
+
LIMIT_TEXT_EDITS_PER_USER,
|
| 51 |
+
LIMIT_TREE_CHANGES_PER_USER,
|
| 52 |
+
LIMIT_UPLOADS_PER_DAY,
|
| 53 |
+
LIMIT_UPLOADS_PER_USER,
|
| 54 |
+
MAX_EDITED_TEXT_CHARS,
|
| 55 |
+
)
|
| 56 |
+
from backend.vfs_tree import tree_add_file, tree_add_folder, tree_has_folder, tree_move_path, tree_remove_path
|
| 57 |
+
|
| 58 |
+
logger = logging.getLogger(__name__)
|
| 59 |
+
router = APIRouter()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _error(message: str, status_code: int = 400) -> JSONResponse:
|
| 63 |
+
return JSONResponse({"error": message}, status_code=status_code)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _under(prefix: str):
|
| 67 |
+
return lambda p: (p or "").replace("\\", "/") == prefix or (p or "").replace("\\", "/").startswith(prefix + "/")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@router.get("/list_tree")
|
| 71 |
+
def list_tree(effective: EffectiveUser = None):
|
| 72 |
+
user_id, _ = effective
|
| 73 |
+
return {"tree": get_vfs_tree_clean(user_id)}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@router.post("/create_folder")
|
| 77 |
+
def create_folder(path: str = Form(""), name: str = Form(...), user_id: SignedInUser = None):
|
| 78 |
+
rate_limit.check("tree-changes", user_id, *LIMIT_TREE_CHANGES_PER_USER)
|
| 79 |
+
path = strip_storage_path(path)
|
| 80 |
+
name = (name or "").strip().replace("\\", "/").strip("/")
|
| 81 |
+
if not valid_name(name):
|
| 82 |
+
return _error("Invalid folder name.")
|
| 83 |
+
with user_lock(user_id):
|
| 84 |
+
tree = get_vfs_tree_clean(user_id)
|
| 85 |
+
if path and not tree_has_folder(tree, path):
|
| 86 |
+
return _error(f"Folder '{path}' does not exist.")
|
| 87 |
+
vfs_set_tree(user_id, tree_add_folder(tree, path, name))
|
| 88 |
+
return JSONResponse({"message": f"Folder '{name}' created.", "path": join_path(path, name)})
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@router.post("/create_file")
|
| 92 |
+
def create_file(path: str = Form(""), name: str = Form(...), user_id: SignedInUser = None):
|
| 93 |
+
rate_limit.check("tree-changes", user_id, *LIMIT_TREE_CHANGES_PER_USER)
|
| 94 |
+
path = strip_storage_path(path)
|
| 95 |
+
if path and ".." in path:
|
| 96 |
+
return _error("Invalid path.")
|
| 97 |
+
name = (name or "").strip()
|
| 98 |
+
filename = name if "." in name else f"{name}.txt"
|
| 99 |
+
if not name or not valid_name(filename):
|
| 100 |
+
return _error("Invalid file name.")
|
| 101 |
+
rel_path = join_path(path, filename)
|
| 102 |
+
with user_lock(user_id):
|
| 103 |
+
tree = get_vfs_tree_clean(user_id)
|
| 104 |
+
if path and not tree_has_folder(tree, path):
|
| 105 |
+
return _error(f"Folder '{path}' does not exist.")
|
| 106 |
+
if path_exists_in_vfs(tree, rel_path):
|
| 107 |
+
return _error(f"'{filename}' already exists here.")
|
| 108 |
+
vfs_set_tree(user_id, tree_add_file(tree, path, filename))
|
| 109 |
+
user_document_upsert(user_id, rel_path, "", filename)
|
| 110 |
+
return JSONResponse({"message": f"File '{filename}' created.", "path": rel_path})
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@router.post("/upload_note")
|
| 114 |
+
def upload_note(path: str = Form(""), file: UploadFile = File(...), user_id: SignedInUser = None):
|
| 115 |
+
"""Check and queue an upload; the text is read in the background (see GET /jobs/{job_id})."""
|
| 116 |
+
rate_limit.per_user(
|
| 117 |
+
user_id,
|
| 118 |
+
("upload", LIMIT_UPLOADS_PER_USER, None),
|
| 119 |
+
("upload-day", LIMIT_UPLOADS_PER_DAY, "uploads"),
|
| 120 |
+
)
|
| 121 |
+
path = strip_storage_path(path)
|
| 122 |
+
if path and ".." in path:
|
| 123 |
+
return _error("Invalid path.")
|
| 124 |
+
tree = get_vfs_tree_clean(user_id)
|
| 125 |
+
if path and not tree_has_folder(tree, path):
|
| 126 |
+
return _error(f"Folder '{path}' does not exist.")
|
| 127 |
+
raw_name = uploads.clean_upload_name(file)
|
| 128 |
+
uploads.check_supported_type(raw_name)
|
| 129 |
+
usage.check_budget()
|
| 130 |
+
data = uploads.read_upload(file)
|
| 131 |
+
job = uploads.submit_upload_job(user_id, path, raw_name, data)
|
| 132 |
+
usage.record(user_id, uploads=1)
|
| 133 |
+
return JSONResponse(job, status_code=202)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@router.get("/jobs")
|
| 137 |
+
def list_jobs(user_id: SignedInUser = None):
|
| 138 |
+
return {"jobs": uploads.list_jobs(user_id)}
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@router.get("/jobs/{job_id}")
|
| 142 |
+
def get_job(job_id: str, user_id: SignedInUser = None):
|
| 143 |
+
job = uploads.get_job(user_id, job_id)
|
| 144 |
+
if not job:
|
| 145 |
+
return _error("Upload not found (it may have finished more than an hour ago).", 404)
|
| 146 |
+
return job
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _relocate_data(user_id: str, tree: list, kind: str, src: str, dest: str) -> None:
|
| 150 |
+
"""Move search chunks, stored text and metadata from src to dest (file or whole folder)."""
|
| 151 |
+
if kind == "file":
|
| 152 |
+
chunks_relocate_path(user_id, src, dest)
|
| 153 |
+
user_document_rename_path(user_id, src, dest)
|
| 154 |
+
file_meta_rename_path(user_id, src, dest)
|
| 155 |
+
else:
|
| 156 |
+
chunks_relocate_files(user_id, file_paths(tree), src, dest)
|
| 157 |
+
user_documents_relocate_prefix(user_id, src, dest)
|
| 158 |
+
file_meta_relocate_prefix(user_id, src, dest)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
@router.post("/delete_path")
|
| 162 |
+
def delete_path(path: str = Form(...), kind: str = Form(...), user_id: SignedInUser = None):
|
| 163 |
+
"""Remove a file or folder from the virtual tree and Chroma (no server-side binaries)."""
|
| 164 |
+
rate_limit.check("tree-changes", user_id, *LIMIT_TREE_CHANGES_PER_USER)
|
| 165 |
+
path = strip_storage_path(path)
|
| 166 |
+
if not path or ".." in path:
|
| 167 |
+
return _error("Invalid path.")
|
| 168 |
+
if kind not in ("file", "folder"):
|
| 169 |
+
return _error("Invalid kind. Use 'file' or 'folder'.")
|
| 170 |
+
with user_lock(user_id):
|
| 171 |
+
tree = get_vfs_tree_clean(user_id)
|
| 172 |
+
if vfs_entry_kind(tree, path) != kind:
|
| 173 |
+
return _error(f"Not a {kind} or not found.")
|
| 174 |
+
# Data is removed before the tree entry: if a step fails, the item stays visible and can be retried.
|
| 175 |
+
if kind == "file":
|
| 176 |
+
delete_user_notes_by_paths(user_id, [path])
|
| 177 |
+
user_document_delete_by_path(user_id, path)
|
| 178 |
+
delete_key(user_id, path)
|
| 179 |
+
else:
|
| 180 |
+
delete_user_notes_by_paths(user_id, [p for p in file_paths(tree) if _under(path)(p)])
|
| 181 |
+
user_document_delete_many(user_id, path_filter=_under(path))
|
| 182 |
+
delete_keys_for_prefix(user_id, path)
|
| 183 |
+
vfs_set_tree(user_id, tree_remove_path(tree, path))
|
| 184 |
+
return JSONResponse({"message": "File deleted." if kind == "file" else "Folder deleted."})
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
@router.post("/move_path")
|
| 188 |
+
def move_path(from_path: str = Form(...), to_folder: str = Form(""), user_id: SignedInUser = None):
|
| 189 |
+
"""Move a file or folder in the virtual tree and update Chroma paths."""
|
| 190 |
+
rate_limit.check("tree-changes", user_id, *LIMIT_TREE_CHANGES_PER_USER)
|
| 191 |
+
from_path = strip_storage_path(from_path)
|
| 192 |
+
to_folder = strip_storage_path(to_folder)
|
| 193 |
+
if ".." in from_path or ".." in to_folder:
|
| 194 |
+
return _error("Invalid path.")
|
| 195 |
+
with user_lock(user_id):
|
| 196 |
+
tree = get_vfs_tree_clean(user_id)
|
| 197 |
+
kind = vfs_entry_kind(tree, from_path)
|
| 198 |
+
if not kind:
|
| 199 |
+
return _error("Path not found.")
|
| 200 |
+
if kind == "folder" and (to_folder == from_path or to_folder.startswith(from_path + "/")):
|
| 201 |
+
return _error("A folder can't be moved into itself.")
|
| 202 |
+
name = os.path.basename(from_path)
|
| 203 |
+
dest_rel = join_path(to_folder, name)
|
| 204 |
+
if dest_rel == from_path:
|
| 205 |
+
return JSONResponse({"message": "Already there.", "path": dest_rel})
|
| 206 |
+
if path_exists_in_vfs(tree, dest_rel):
|
| 207 |
+
return _error(f"'{name}' already exists in destination.")
|
| 208 |
+
# Move the data first, then the tree entry, so the tree never points at data that isn't there.
|
| 209 |
+
_relocate_data(user_id, tree, kind, from_path, dest_rel)
|
| 210 |
+
vfs_set_tree(user_id, tree_move_path(tree, from_path, to_folder))
|
| 211 |
+
return JSONResponse({"message": "Moved.", "path": dest_rel})
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
@router.post("/rename_path")
|
| 215 |
+
def rename_path(path: str = Form(...), new_name: str = Form(...), user_id: SignedInUser = None):
|
| 216 |
+
rate_limit.check("tree-changes", user_id, *LIMIT_TREE_CHANGES_PER_USER)
|
| 217 |
+
path = strip_storage_path(path)
|
| 218 |
+
new_name = (new_name or "").strip()
|
| 219 |
+
if not path or ".." in path:
|
| 220 |
+
return _error("Invalid path.")
|
| 221 |
+
if not valid_name(new_name):
|
| 222 |
+
return _error("Names can't be empty or contain '/' or '..'.")
|
| 223 |
+
with user_lock(user_id):
|
| 224 |
+
tree = get_vfs_tree_clean(user_id)
|
| 225 |
+
kind = vfs_entry_kind(tree, path)
|
| 226 |
+
if not kind:
|
| 227 |
+
return _error("Path not found.")
|
| 228 |
+
parent = parent_of(path)
|
| 229 |
+
dest = join_path(parent, new_name)
|
| 230 |
+
if dest == path:
|
| 231 |
+
return JSONResponse({"message": "Name unchanged.", "path": dest, "kind": kind})
|
| 232 |
+
if path_exists_in_vfs(tree, dest):
|
| 233 |
+
return _error(f"'{new_name}' already exists here.")
|
| 234 |
+
_relocate_data(user_id, tree, kind, path, dest)
|
| 235 |
+
vfs_set_tree(user_id, tree_move_path(tree, path, parent, new_name=new_name))
|
| 236 |
+
return JSONResponse({"message": "Renamed.", "path": dest, "kind": kind})
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@router.get("/file_text")
|
| 240 |
+
def get_file_text(path: str = "", user_id: SignedInUser = None):
|
| 241 |
+
"""The text NoteScanner has for a file (what search and study tools use)."""
|
| 242 |
+
p = strip_storage_path(path)
|
| 243 |
+
if vfs_entry_kind(get_vfs_tree_clean(user_id), p) != "file":
|
| 244 |
+
return _error("File not found.", 404)
|
| 245 |
+
doc = user_document_get(user_id, p)
|
| 246 |
+
if doc and not doc["truncated"]:
|
| 247 |
+
return {"path": p, "text": doc["content"], "truncated": False}
|
| 248 |
+
# Older uploads only kept the first part of the text; rebuild the rest from the search chunks.
|
| 249 |
+
chunk_text = user_notes_concat_text_for_path(user_id, p)
|
| 250 |
+
if chunk_text:
|
| 251 |
+
return {"path": p, "text": chunk_text, "truncated": False}
|
| 252 |
+
return {"path": p, "text": doc["content"] if doc else "", "truncated": bool(doc)}
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
@router.post("/file_text")
|
| 256 |
+
def save_file_text(path: str = Form(...), text: str = Form(""), user_id: SignedInUser = None):
|
| 257 |
+
"""Replace a file's text (e.g. to fix reading mistakes, or to write notes in an empty file)."""
|
| 258 |
+
rate_limit.check("text-edits", user_id, *LIMIT_TEXT_EDITS_PER_USER)
|
| 259 |
+
p = strip_storage_path(path)
|
| 260 |
+
if len(text) > MAX_EDITED_TEXT_CHARS:
|
| 261 |
+
return _error(f"Text is too long (maximum {MAX_EDITED_TEXT_CHARS:,} characters).")
|
| 262 |
+
tree = get_vfs_tree_clean(user_id)
|
| 263 |
+
if vfs_entry_kind(tree, p) != "file":
|
| 264 |
+
return _error("File not found.", 404)
|
| 265 |
+
name = os.path.basename(p)
|
| 266 |
+
if text.strip():
|
| 267 |
+
chunks = ingest_text_for_path(user_id, p, name, text)["chunks_created"]
|
| 268 |
+
else:
|
| 269 |
+
delete_user_notes_by_paths(user_id, [p])
|
| 270 |
+
chunks = 0
|
| 271 |
+
user_document_upsert(user_id, p, text, name)
|
| 272 |
+
return JSONResponse({"message": "Saved.", "chunks": chunks})
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
@router.get("/file_meta")
|
| 276 |
+
def get_file_meta_route(effective: EffectiveUser = None):
|
| 277 |
+
user_id, _ = effective
|
| 278 |
+
return {"meta": load_file_meta(user_id)}
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
@router.post("/file_meta")
|
| 282 |
+
def post_file_meta(
|
| 283 |
+
path: str = Form(...),
|
| 284 |
+
is_primary_authority: str = Form("false"),
|
| 285 |
+
doc_type: str = Form(""),
|
| 286 |
+
related_paths: str = Form(""),
|
| 287 |
+
user_id: SignedInUser = None,
|
| 288 |
+
):
|
| 289 |
+
rate_limit.check("tree-changes", user_id, *LIMIT_TREE_CHANGES_PER_USER)
|
| 290 |
+
path = strip_storage_path(path)
|
| 291 |
+
primary = str(is_primary_authority).lower() in ("1", "true", "yes", "on")
|
| 292 |
+
rel_list = [strip_storage_path(x.strip()) for x in related_paths.split(",") if x.strip()]
|
| 293 |
+
entry = set_entry(
|
| 294 |
+
user_id,
|
| 295 |
+
path,
|
| 296 |
+
is_primary_authority=primary,
|
| 297 |
+
doc_type=(doc_type or "other"),
|
| 298 |
+
related_paths=rel_list,
|
| 299 |
+
)
|
| 300 |
+
n = refresh_metadata_for_paths(user_id, [path])
|
| 301 |
+
return JSONResponse({"path": path, "entry": entry, "chunks_updated": n})
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
@router.delete("/notes")
|
| 305 |
+
def delete_notes(file: str | None = None, files: str | None = None, user_id: SignedInUser = None):
|
| 306 |
+
"""
|
| 307 |
+
Delete the user's notes.
|
| 308 |
+
- No query params: delete all notes, folders and stored text.
|
| 309 |
+
- file=<path> / files=<path1>,<path2>: delete only the search chunks for those paths.
|
| 310 |
+
"""
|
| 311 |
+
if file or files:
|
| 312 |
+
paths = [p.strip() for p in ([file] if file else files.split(",")) if p and p.strip()]
|
| 313 |
+
if not paths:
|
| 314 |
+
return _error("No paths provided.")
|
| 315 |
+
if any(".." in p or p.startswith("/") for p in paths):
|
| 316 |
+
return _error("Invalid path.")
|
| 317 |
+
deleted = delete_user_notes_by_paths(user_id, [strip_storage_path(p) for p in paths])
|
| 318 |
+
return JSONResponse({"message": f"Deleted {deleted} chunk(s) for the given file(s).", "deleted_count": deleted})
|
| 319 |
+
rate_limit.check("delete-all", user_id, *LIMIT_DELETE_ALL_PER_USER)
|
| 320 |
+
with user_lock(user_id):
|
| 321 |
+
deleted_notes = delete_user_notes_collection(user_id)
|
| 322 |
+
deleted_vfs = delete_user_vfs_collection(user_id)
|
| 323 |
+
user_document_delete_many(user_id, path_filter=None)
|
| 324 |
+
legacy_migration.forget_user(user_id)
|
| 325 |
+
return JSONResponse({
|
| 326 |
+
"message": "All your notes have been deleted.",
|
| 327 |
+
"deleted_notes": deleted_notes,
|
| 328 |
+
"deleted_vfs": deleted_vfs,
|
| 329 |
+
})
|
backend/routes/library.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The shared course library: which PDFs are ready for questions, and admin controls for indexing."""
|
| 2 |
+
from fastapi import APIRouter, Form
|
| 3 |
+
|
| 4 |
+
from backend import library, settings
|
| 5 |
+
from backend.deps import SignedInUser
|
| 6 |
+
from backend.routes.admin import _require_admin
|
| 7 |
+
|
| 8 |
+
router = APIRouter()
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@router.get("/library/status")
|
| 12 |
+
def library_status():
|
| 13 |
+
"""Public: the course PDFs (storage paths) students can ask about. No account needed."""
|
| 14 |
+
return library.public_status()
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@router.get("/admin/library")
|
| 18 |
+
def admin_library(user_id: SignedInUser = None):
|
| 19 |
+
"""Per-file indexing details and the last sync's summary (admins only)."""
|
| 20 |
+
_require_admin(user_id)
|
| 21 |
+
files = library.indexed_files()
|
| 22 |
+
by_status: dict[str, int] = {}
|
| 23 |
+
for m in files.values():
|
| 24 |
+
by_status[m.get("status") or "unknown"] = by_status.get(m.get("status") or "unknown", 0) + 1
|
| 25 |
+
keep = ("path", "status", "pages", "ocr_pieces", "sarvam_pieces", "chunks", "method", "error", "updated_at")
|
| 26 |
+
return {
|
| 27 |
+
"enabled": settings.LIBRARY_ENABLED,
|
| 28 |
+
"ocr": library._ocr_mode(),
|
| 29 |
+
"sync_hours": settings.LIBRARY_SYNC_HOURS,
|
| 30 |
+
"by_status": by_status,
|
| 31 |
+
"sync": library.sync_state(),
|
| 32 |
+
"files": sorted(({k: m.get(k) for k in keep} for m in files.values()), key=lambda f: f["path"]),
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@router.post("/admin/library/sync")
|
| 37 |
+
def admin_library_sync(force: bool = Form(False), user_id: SignedInUser = None):
|
| 38 |
+
"""Start indexing new or changed course PDFs in the background (admins only)."""
|
| 39 |
+
_require_admin(user_id)
|
| 40 |
+
started = library.sync_in_background(force=force)
|
| 41 |
+
return {
|
| 42 |
+
"started": started,
|
| 43 |
+
"message": "Library sync started." if started else "A library sync is already running.",
|
| 44 |
+
"sync": library.sync_state(),
|
| 45 |
+
}
|
backend/routes/onenote.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Microsoft OneNote: connect (OAuth) and import pages as notes."""
|
| 2 |
+
import html
|
| 3 |
+
import logging
|
| 4 |
+
import time
|
| 5 |
+
import uuid
|
| 6 |
+
|
| 7 |
+
from fastapi import APIRouter, Form
|
| 8 |
+
from fastapi.responses import HTMLResponse, JSONResponse
|
| 9 |
+
|
| 10 |
+
from backend import onenote_sync, rate_limit
|
| 11 |
+
from backend.chroma_store import (
|
| 12 |
+
onenote_oauth_state_create,
|
| 13 |
+
onenote_oauth_state_pop_user_id,
|
| 14 |
+
onenote_token_get,
|
| 15 |
+
onenote_token_upsert,
|
| 16 |
+
)
|
| 17 |
+
from backend.deps import EffectiveUser, SignedInUser
|
| 18 |
+
from backend.settings import LIMIT_ONENOTE_CONNECT_PER_USER, LIMIT_ONENOTE_SYNC_PER_USER
|
| 19 |
+
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
router = APIRouter()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@router.get("/integrations/onenote/status")
|
| 25 |
+
def onenote_status(effective: EffectiveUser = None):
|
| 26 |
+
user_id, is_guest = effective
|
| 27 |
+
connected = False
|
| 28 |
+
if not is_guest:
|
| 29 |
+
connected = bool(onenote_token_get(user_id))
|
| 30 |
+
return {
|
| 31 |
+
"configured": onenote_sync.is_configured(),
|
| 32 |
+
"connected": connected,
|
| 33 |
+
"requires_sign_in": is_guest,
|
| 34 |
+
"redirect_uri": onenote_sync.redirect_uri(),
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@router.get("/integrations/onenote/auth_url")
|
| 39 |
+
def onenote_auth_url(user_id: SignedInUser = None):
|
| 40 |
+
rate_limit.check("onenote-connect", user_id, *LIMIT_ONENOTE_CONNECT_PER_USER)
|
| 41 |
+
if not onenote_sync.is_configured():
|
| 42 |
+
return JSONResponse({"error": "Microsoft OAuth is not configured on server."}, status_code=503)
|
| 43 |
+
state = str(uuid.uuid4())
|
| 44 |
+
onenote_oauth_state_create(user_id, state, int(time.time()) + 600)
|
| 45 |
+
return {"auth_url": onenote_sync.build_auth_url(state), "state": state}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _onenote_page(title: str, message: str, status_code: int = 200) -> HTMLResponse:
|
| 49 |
+
"""Small HTML page for the OAuth popup. Text is escaped because it can come from the URL."""
|
| 50 |
+
body = (
|
| 51 |
+
f"<html><body><h3>{html.escape(title)}</h3>"
|
| 52 |
+
f"<p>{html.escape(message)}</p><p>You can close this tab.</p></body></html>"
|
| 53 |
+
)
|
| 54 |
+
return HTMLResponse(content=body, status_code=status_code)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@router.get("/integrations/onenote/callback")
|
| 58 |
+
def onenote_callback(code: str = "", state: str = "", error: str = "", error_description: str = ""):
|
| 59 |
+
if error:
|
| 60 |
+
return _onenote_page("OneNote connect failed", error_description or error, 400)
|
| 61 |
+
if not code or not state:
|
| 62 |
+
return _onenote_page("Missing OAuth parameters.", "Please restart the connection.", 400)
|
| 63 |
+
user_id = onenote_oauth_state_pop_user_id(state)
|
| 64 |
+
if not user_id:
|
| 65 |
+
return _onenote_page("OAuth state is invalid or expired.", "Please restart the connection.", 400)
|
| 66 |
+
try:
|
| 67 |
+
token_payload = onenote_sync.exchange_code_for_token(code)
|
| 68 |
+
onenote_token_upsert(user_id, token_payload)
|
| 69 |
+
return _onenote_page("OneNote connected successfully.", "Return to NoteScanner to sync your pages.")
|
| 70 |
+
except Exception as e:
|
| 71 |
+
logger.exception("OneNote token exchange failed")
|
| 72 |
+
return _onenote_page("Token exchange failed.", str(e), 500)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@router.post("/integrations/onenote/sync")
|
| 76 |
+
def onenote_sync_route(max_pages: int = Form(25), user_id: SignedInUser = None):
|
| 77 |
+
rate_limit.check("onenote-sync", user_id, *LIMIT_ONENOTE_SYNC_PER_USER)
|
| 78 |
+
if not onenote_sync.is_configured():
|
| 79 |
+
return JSONResponse({"error": "Microsoft OAuth is not configured on server."}, status_code=503)
|
| 80 |
+
try:
|
| 81 |
+
out = onenote_sync.sync_onenote_pages_to_ingest(user_id, max_pages=max_pages)
|
| 82 |
+
return JSONResponse({"message": "OneNote sync complete.", **out})
|
| 83 |
+
except Exception as e:
|
| 84 |
+
logger.exception("OneNote sync failed")
|
| 85 |
+
return JSONResponse({"error": str(e)}, status_code=500)
|
backend/routes/study.py
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Study tools: flashcards, MCQs, summaries, saved decks, the Today dashboard and exam mode."""
|
| 2 |
+
import datetime as dt
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
from fastapi import APIRouter, Form
|
| 8 |
+
from fastapi.responses import JSONResponse, Response
|
| 9 |
+
|
| 10 |
+
from backend import alerts, library, llm_pipeline, preferences, rate_limit, study_store, usage
|
| 11 |
+
from backend.chroma_store import user_document_get_content, user_notes_concat_text_for_path
|
| 12 |
+
from backend.deps import SignedInUser
|
| 13 |
+
from backend.paths import file_paths, get_vfs_tree_clean, strip_storage_path
|
| 14 |
+
from backend.settings import LIMIT_DECK_CHANGES_PER_USER, LIMIT_STUDY_PER_DAY, LIMIT_STUDY_PER_USER
|
| 15 |
+
|
| 16 |
+
router = APIRouter()
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _study_text_for_path(user_id: str, rel_path: str) -> str:
|
| 20 |
+
"""Prefer Chroma chunk text (same as RAG), fall back to user_documents."""
|
| 21 |
+
p = strip_storage_path(rel_path or "")
|
| 22 |
+
if not p:
|
| 23 |
+
return ""
|
| 24 |
+
chunk = (user_notes_concat_text_for_path(user_id, p) or "").strip()
|
| 25 |
+
if chunk:
|
| 26 |
+
return chunk
|
| 27 |
+
return (user_document_get_content(user_id, p) or "").strip()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _build_study_scope_context(
|
| 31 |
+
user_id: str,
|
| 32 |
+
opened_file_path: str,
|
| 33 |
+
course_path: str,
|
| 34 |
+
focus_query: str,
|
| 35 |
+
include_course_context: bool,
|
| 36 |
+
library_path: str = "",
|
| 37 |
+
) -> tuple[str | None, str | None]:
|
| 38 |
+
"""Return context strictly from opened file and optionally same course folder."""
|
| 39 |
+
if (library_path or "").strip():
|
| 40 |
+
focus = (focus_query or "").strip() or "key ideas for exam"
|
| 41 |
+
return library.study_context(library_path, focus, include_course_context)
|
| 42 |
+
open_rel = strip_storage_path(opened_file_path or "")
|
| 43 |
+
if not open_rel:
|
| 44 |
+
return None, "Open a file first. Study generation uses the active file context."
|
| 45 |
+
|
| 46 |
+
all_paths = file_paths(get_vfs_tree_clean(user_id))
|
| 47 |
+
if open_rel not in set(all_paths):
|
| 48 |
+
return None, f"Active file '{open_rel}' was not found in your notes."
|
| 49 |
+
|
| 50 |
+
root_course = strip_storage_path(course_path or "")
|
| 51 |
+
if not root_course:
|
| 52 |
+
root_course = open_rel.split("/", 1)[0] if "/" in open_rel else open_rel
|
| 53 |
+
# Root course is only a top-level folder scope, never a file path.
|
| 54 |
+
root_course = root_course.split("/", 1)[0] if root_course else ""
|
| 55 |
+
|
| 56 |
+
open_text = (_study_text_for_path(user_id, open_rel) or "").strip()
|
| 57 |
+
if not open_text:
|
| 58 |
+
return None, (
|
| 59 |
+
f"No text found for '{open_rel}'. Open it in Text view to add some, or upload it again."
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
focus = (focus_query or "").strip() or "key ideas for exam"
|
| 63 |
+
parts = [
|
| 64 |
+
f"Focus: {focus}",
|
| 65 |
+
f"Active course folder: {root_course or '(root)'}",
|
| 66 |
+
f"Primary file: {open_rel}",
|
| 67 |
+
"",
|
| 68 |
+
"--- PRIMARY FILE CONTENT ---",
|
| 69 |
+
open_text[:35000],
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
if include_course_context and root_course:
|
| 73 |
+
prefix = root_course + "/"
|
| 74 |
+
extra_paths = [p for p in all_paths if p != open_rel and (p == root_course or p.startswith(prefix))]
|
| 75 |
+
if extra_paths:
|
| 76 |
+
budget = 25000
|
| 77 |
+
extras: list[str] = []
|
| 78 |
+
for p in extra_paths:
|
| 79 |
+
if budget <= 0:
|
| 80 |
+
break
|
| 81 |
+
t = _study_text_for_path(user_id, p)
|
| 82 |
+
if not t:
|
| 83 |
+
continue
|
| 84 |
+
chunk = t[: min(len(t), 3500, budget)]
|
| 85 |
+
if not chunk.strip():
|
| 86 |
+
continue
|
| 87 |
+
extras.append(f"--- COURSE SUPPORTING FILE: {p} ---\n{chunk}")
|
| 88 |
+
budget -= len(chunk)
|
| 89 |
+
if extras:
|
| 90 |
+
parts.append("")
|
| 91 |
+
parts.append("--- OPTIONAL SAME-COURSE SUPPORT ---")
|
| 92 |
+
parts.append("\n\n".join(extras))
|
| 93 |
+
|
| 94 |
+
return "\n".join(parts)[:60000], None
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _limit_study(user_id: str) -> None:
|
| 98 |
+
rate_limit.per_user(
|
| 99 |
+
user_id,
|
| 100 |
+
("study", LIMIT_STUDY_PER_USER, None),
|
| 101 |
+
("study-day", LIMIT_STUDY_PER_DAY, "flashcard, quiz and summary requests"),
|
| 102 |
+
)
|
| 103 |
+
usage.check_budget()
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _run_study_ai(user_id: str, fn, *args):
|
| 107 |
+
"""Call a study AI function in the student's language and count its use. Returns (data, err)."""
|
| 108 |
+
llm_pipeline.take_usage()
|
| 109 |
+
data, err = fn(*args, **preferences.language_kwargs(user_id))
|
| 110 |
+
usage.record(user_id, study_requests=1, **llm_pipeline.take_usage())
|
| 111 |
+
if err:
|
| 112 |
+
alerts.notify("ai-unavailable", f"Study generation failed: {err}")
|
| 113 |
+
return data, err
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@router.post("/study/generate")
|
| 117 |
+
def study_generate(
|
| 118 |
+
task: str = Form("flashcards"),
|
| 119 |
+
count: int = Form(5),
|
| 120 |
+
focus_query: str = Form("key ideas for exam"),
|
| 121 |
+
opened_file_path: str = Form(""),
|
| 122 |
+
course_path: str = Form(""),
|
| 123 |
+
include_course_context: bool = Form(True),
|
| 124 |
+
library_path: str = Form(""),
|
| 125 |
+
user_id: SignedInUser = None,
|
| 126 |
+
):
|
| 127 |
+
if task not in ("flashcards", "mcq"):
|
| 128 |
+
return JSONResponse({"error": "task must be 'flashcards' or 'mcq'."}, status_code=400)
|
| 129 |
+
_limit_study(user_id)
|
| 130 |
+
ctx, cerr = _build_study_scope_context(
|
| 131 |
+
user_id, opened_file_path, course_path, focus_query, include_course_context, library_path
|
| 132 |
+
)
|
| 133 |
+
if cerr:
|
| 134 |
+
return JSONResponse({"error": cerr}, status_code=400)
|
| 135 |
+
data, err = _run_study_ai(user_id, llm_pipeline.cheap_study_json, ctx, task, max(1, min(count, 30)))
|
| 136 |
+
if err:
|
| 137 |
+
return JSONResponse({"error": err}, status_code=503)
|
| 138 |
+
return JSONResponse(
|
| 139 |
+
{
|
| 140 |
+
"task": task,
|
| 141 |
+
"items": data,
|
| 142 |
+
"grounded_on_path": _grounded_on(opened_file_path, library_path),
|
| 143 |
+
"context_chars": len(ctx or ""),
|
| 144 |
+
}
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _grounded_on(opened_file_path: str, library_path: str) -> str:
|
| 149 |
+
return library.scope_of(library_path)[0] or strip_storage_path(opened_file_path or "")
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _summary(
|
| 153 |
+
user_id: str,
|
| 154 |
+
focus_query: str,
|
| 155 |
+
opened_file_path: str,
|
| 156 |
+
course_path: str,
|
| 157 |
+
include_course_context: bool,
|
| 158 |
+
library_path: str = "",
|
| 159 |
+
):
|
| 160 |
+
_limit_study(user_id)
|
| 161 |
+
focus = (focus_query or "").strip() or "main concepts"
|
| 162 |
+
ctx, cerr = _build_study_scope_context(
|
| 163 |
+
user_id, opened_file_path, course_path, focus, include_course_context, library_path
|
| 164 |
+
)
|
| 165 |
+
if cerr:
|
| 166 |
+
return JSONResponse({"error": cerr}, status_code=400)
|
| 167 |
+
summary_text, err = _run_study_ai(user_id, llm_pipeline.topic_summary, ctx)
|
| 168 |
+
if err:
|
| 169 |
+
return JSONResponse({"error": err}, status_code=503)
|
| 170 |
+
return JSONResponse(
|
| 171 |
+
{
|
| 172 |
+
"summary": summary_text,
|
| 173 |
+
"grounded_on_path": _grounded_on(opened_file_path, library_path),
|
| 174 |
+
"context_chars": len(ctx or ""),
|
| 175 |
+
}
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
@router.post("/study/summary")
|
| 180 |
+
def study_summary(
|
| 181 |
+
focus_query: str = Form("main concepts"),
|
| 182 |
+
opened_file_path: str = Form(""),
|
| 183 |
+
course_path: str = Form(""),
|
| 184 |
+
include_course_context: bool = Form(True),
|
| 185 |
+
library_path: str = Form(""),
|
| 186 |
+
user_id: SignedInUser = None,
|
| 187 |
+
):
|
| 188 |
+
return _summary(user_id, focus_query, opened_file_path, course_path, include_course_context, library_path)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
@router.post("/study/mindmap", deprecated=True)
|
| 192 |
+
def study_mindmap(
|
| 193 |
+
focus_query: str = Form("main concepts"),
|
| 194 |
+
opened_file_path: str = Form(""),
|
| 195 |
+
course_path: str = Form(""),
|
| 196 |
+
include_course_context: bool = Form(True),
|
| 197 |
+
user_id: SignedInUser = None,
|
| 198 |
+
):
|
| 199 |
+
"""Old name for /study/summary, kept so older frontends keep working."""
|
| 200 |
+
return _summary(user_id, focus_query, opened_file_path, course_path, include_course_context)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
# ---------- Saved decks + spaced repetition ----------
|
| 204 |
+
@router.post("/study/decks")
|
| 205 |
+
def create_deck(name: str = Form(""), source_path: str = Form(""), cards: str = Form(...), user_id: SignedInUser = None):
|
| 206 |
+
rate_limit.check("deck-changes", user_id, *LIMIT_DECK_CHANGES_PER_USER)
|
| 207 |
+
try:
|
| 208 |
+
parsed = json.loads(cards)
|
| 209 |
+
except json.JSONDecodeError:
|
| 210 |
+
return JSONResponse({"error": "cards must be a JSON list."}, status_code=400)
|
| 211 |
+
if not isinstance(parsed, list):
|
| 212 |
+
return JSONResponse({"error": "cards must be a JSON list."}, status_code=400)
|
| 213 |
+
try:
|
| 214 |
+
deck = study_store.create_deck(user_id, name, strip_storage_path(source_path), [c for c in parsed if isinstance(c, dict)])
|
| 215 |
+
except ValueError as e:
|
| 216 |
+
return JSONResponse({"error": str(e)}, status_code=400)
|
| 217 |
+
return JSONResponse(deck, status_code=201)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
@router.get("/study/decks")
|
| 221 |
+
def list_decks(user_id: SignedInUser = None):
|
| 222 |
+
return {"decks": study_store.list_decks(user_id)}
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
@router.get("/study/decks/{deck_id}/cards")
|
| 226 |
+
def deck_cards(deck_id: str, due_only: bool = False, limit: int = 50, user_id: SignedInUser = None):
|
| 227 |
+
cards = study_store.deck_cards(user_id, deck_id, due_only, limit)
|
| 228 |
+
if cards is None:
|
| 229 |
+
return JSONResponse({"error": "Deck not found."}, status_code=404)
|
| 230 |
+
return {"cards": cards}
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
@router.post("/study/cards/{card_id}/review")
|
| 234 |
+
def review_card(card_id: str, grade: str = Form(...), user_id: SignedInUser = None):
|
| 235 |
+
try:
|
| 236 |
+
result = study_store.review_card(user_id, card_id, (grade or "").strip().lower())
|
| 237 |
+
except ValueError as e:
|
| 238 |
+
return JSONResponse({"error": str(e)}, status_code=400)
|
| 239 |
+
if result is None:
|
| 240 |
+
return JSONResponse({"error": "Card not found."}, status_code=404)
|
| 241 |
+
usage.record(user_id, reviews=1)
|
| 242 |
+
return result
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@router.delete("/study/decks/{deck_id}")
|
| 246 |
+
def delete_deck(deck_id: str, user_id: SignedInUser = None):
|
| 247 |
+
rate_limit.check("deck-changes", user_id, *LIMIT_DECK_CHANGES_PER_USER)
|
| 248 |
+
if not study_store.delete_deck(user_id, deck_id):
|
| 249 |
+
return JSONResponse({"error": "Deck not found."}, status_code=404)
|
| 250 |
+
return {"message": "Deck deleted."}
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
@router.get("/study/decks/{deck_id}/export")
|
| 254 |
+
def export_deck(deck_id: str, user_id: SignedInUser = None):
|
| 255 |
+
"""CSV (front, back) that Anki can import (File → Import)."""
|
| 256 |
+
exported = study_store.export_csv(user_id, deck_id)
|
| 257 |
+
if exported is None:
|
| 258 |
+
return JSONResponse({"error": "Deck not found."}, status_code=404)
|
| 259 |
+
name, csv_text = exported
|
| 260 |
+
filename = (re.sub(r"[^\w\- ]+", "_", name).strip() or "flashcards") + ".csv"
|
| 261 |
+
return Response(
|
| 262 |
+
content=csv_text,
|
| 263 |
+
media_type="text/csv; charset=utf-8",
|
| 264 |
+
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
# ---------- Today dashboard ----------
|
| 269 |
+
def _end_of_today(now: float) -> int:
|
| 270 |
+
tomorrow = usage.today(now) + dt.timedelta(days=1)
|
| 271 |
+
return int(dt.datetime.combine(tomorrow, dt.time(), tzinfo=usage.tz()).timestamp())
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def _active(rec: dict) -> bool:
|
| 275 |
+
return any(int(rec.get(k) or 0) for k in ("reviews", "questions", "study_requests"))
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
@router.get("/study/dashboard")
|
| 279 |
+
def dashboard(user_id: SignedInUser = None):
|
| 280 |
+
now = time.time()
|
| 281 |
+
today = usage.today(now)
|
| 282 |
+
by_day = {r.get("day"): r for r in usage.records_since(today - dt.timedelta(days=90), user_id)}
|
| 283 |
+
|
| 284 |
+
# Streak: consecutive active days ending today (or yesterday, if today hasn't started yet).
|
| 285 |
+
streak = 0
|
| 286 |
+
day = today if _active(by_day.get(today.isoformat(), {})) else today - dt.timedelta(days=1)
|
| 287 |
+
while _active(by_day.get(day.isoformat(), {})):
|
| 288 |
+
streak += 1
|
| 289 |
+
day -= dt.timedelta(days=1)
|
| 290 |
+
|
| 291 |
+
activity = []
|
| 292 |
+
for i in range(13, -1, -1):
|
| 293 |
+
d = (today - dt.timedelta(days=i)).isoformat()
|
| 294 |
+
rec = by_day.get(d, {})
|
| 295 |
+
activity.append({"day": d, "reviews": int(rec.get("reviews") or 0), "questions": int(rec.get("questions") or 0)})
|
| 296 |
+
|
| 297 |
+
upcoming = [e for e in study_store.list_exams(user_id, today) if e["days_left"] >= 0]
|
| 298 |
+
exam = None
|
| 299 |
+
if upcoming:
|
| 300 |
+
e = upcoming[0]
|
| 301 |
+
today_tasks = next((p["tasks"] for p in e["plan"] if p["date"] == today.isoformat()), [])
|
| 302 |
+
exam = {k: e[k] for k in ("exam_id", "course", "exam_date", "days_left")} | {"today": today_tasks}
|
| 303 |
+
|
| 304 |
+
return {
|
| 305 |
+
"due_today": study_store.due_count(user_id, until=_end_of_today(now)),
|
| 306 |
+
"reviewed_today": int(by_day.get(today.isoformat(), {}).get("reviews") or 0),
|
| 307 |
+
"streak_days": streak,
|
| 308 |
+
"decks": len(study_store.list_decks(user_id)),
|
| 309 |
+
"weak_topics": study_store.weak_topics(user_id),
|
| 310 |
+
"activity": activity,
|
| 311 |
+
"exam": exam,
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
@router.post("/study/mcq_results")
|
| 316 |
+
def mcq_results(path: str = Form(...), correct: int = Form(...), total: int = Form(...), user_id: SignedInUser = None):
|
| 317 |
+
"""Record how a quiz went for a file or course folder (feeds "weak topics")."""
|
| 318 |
+
path = strip_storage_path(path)
|
| 319 |
+
if not path or not (0 <= correct <= total <= 100) or total == 0:
|
| 320 |
+
return JSONResponse({"error": "Give a path and 0 ≤ correct ≤ total ≤ 100."}, status_code=400)
|
| 321 |
+
study_store.mcq_record(user_id, path, correct, total)
|
| 322 |
+
return {"message": "Saved."}
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
# ---------- Exam mode ----------
|
| 326 |
+
def _course_files(user_id: str, course_path: str) -> tuple[str, list[str]]:
|
| 327 |
+
course = strip_storage_path(course_path or "")
|
| 328 |
+
paths = file_paths(get_vfs_tree_clean(user_id))
|
| 329 |
+
return course, [p for p in paths if course and (p == course or p.startswith(course + "/"))]
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
@router.post("/study/exam")
|
| 333 |
+
def exam_questions(course_path: str = Form(...), count: int = Form(15), user_id: SignedInUser = None):
|
| 334 |
+
"""A mock test: MCQs drawn from every file in a course folder."""
|
| 335 |
+
course, files = _course_files(user_id, course_path)
|
| 336 |
+
if not files:
|
| 337 |
+
return JSONResponse({"error": "That folder has no files to make questions from."}, status_code=400)
|
| 338 |
+
_limit_study(user_id)
|
| 339 |
+
budget = 50000
|
| 340 |
+
share = max(1500, budget // len(files))
|
| 341 |
+
parts, used = [], []
|
| 342 |
+
for p in files:
|
| 343 |
+
if budget <= 0:
|
| 344 |
+
break
|
| 345 |
+
text = _study_text_for_path(user_id, p)
|
| 346 |
+
if not text:
|
| 347 |
+
continue
|
| 348 |
+
piece = text[: min(share, budget)]
|
| 349 |
+
parts.append(f"--- FILE: {p} ---\n{piece}")
|
| 350 |
+
used.append(p)
|
| 351 |
+
budget -= len(piece)
|
| 352 |
+
if not parts:
|
| 353 |
+
return JSONResponse({"error": "No text found in that folder's files yet."}, status_code=400)
|
| 354 |
+
ctx = f"Mock exam for the course folder: {course}\n\n" + "\n\n".join(parts)
|
| 355 |
+
data, err = _run_study_ai(user_id, llm_pipeline.cheap_study_json, ctx, "mcq", max(5, min(count, 30)))
|
| 356 |
+
if err:
|
| 357 |
+
return JSONResponse({"error": err}, status_code=503)
|
| 358 |
+
return {"items": data, "course": course, "files_used": used}
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
@router.post("/study/exam_plan")
|
| 362 |
+
def exam_plan(course_path: str = Form(...), exam_date: str = Form(...), user_id: SignedInUser = None):
|
| 363 |
+
try:
|
| 364 |
+
exam_day = dt.date.fromisoformat((exam_date or "").strip())
|
| 365 |
+
except ValueError:
|
| 366 |
+
return JSONResponse({"error": "Exam date must look like 2026-11-20."}, status_code=400)
|
| 367 |
+
course, files = _course_files(user_id, course_path)
|
| 368 |
+
if not course:
|
| 369 |
+
return JSONResponse({"error": "Pick a course folder."}, status_code=400)
|
| 370 |
+
rate_limit.check("deck-changes", user_id, *LIMIT_DECK_CHANGES_PER_USER)
|
| 371 |
+
try:
|
| 372 |
+
return study_store.save_exam(user_id, course, files, exam_day, usage.today())
|
| 373 |
+
except ValueError as e:
|
| 374 |
+
return JSONResponse({"error": str(e)}, status_code=400)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
@router.get("/study/exams")
|
| 378 |
+
def list_exams(user_id: SignedInUser = None):
|
| 379 |
+
return {"exams": study_store.list_exams(user_id, usage.today())}
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
@router.delete("/study/exams/{exam_id}")
|
| 383 |
+
def delete_exam(exam_id: str, user_id: SignedInUser = None):
|
| 384 |
+
if not study_store.delete_exam(user_id, exam_id):
|
| 385 |
+
return JSONResponse({"error": "Exam not found."}, status_code=404)
|
| 386 |
+
return {"message": "Exam plan deleted."}
|
backend/search.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Finding the note excerpts that answer a question.
|
| 3 |
+
|
| 4 |
+
Search order: chat uploads (+ button) → the open file → other files in the same course folder →
|
| 5 |
+
all other notes. When the question is about a shared course PDF (SDE-Prep's Notes tab sends its
|
| 6 |
+
path), that PDF and then the rest of its course come first. Every stage is scored as cosine
|
| 7 |
+
similarity (0..1), so stages can be compared.
|
| 8 |
+
"""
|
| 9 |
+
from dataclasses import dataclass, field
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
from backend import library
|
| 14 |
+
from backend.chroma_store import collection_distance_space, distance_to_similarity, get_user_collection
|
| 15 |
+
from backend.ingest_api import embed_texts
|
| 16 |
+
from backend.settings import (
|
| 17 |
+
MAIN_SOURCE_BOOST,
|
| 18 |
+
MIN_SCORE_ALL_NOTES,
|
| 19 |
+
MIN_SCORE_CHAT_UPLOAD,
|
| 20 |
+
MIN_SCORE_COURSE,
|
| 21 |
+
MIN_SCORE_LIBRARY_FILE,
|
| 22 |
+
MIN_SCORE_LIBRARY_SUBJECT,
|
| 23 |
+
MIN_SCORE_OPEN_FILE,
|
| 24 |
+
SOURCE_SCORE_WINDOW,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
MAX_SELECTED = 8
|
| 28 |
+
OPEN_LIBRARY_FILE_LEAD = 0.10 # ranking lead for the course PDF the student has open
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass
|
| 32 |
+
class SearchResult:
|
| 33 |
+
stage: str = ""
|
| 34 |
+
selected: list[dict] = field(default_factory=list)
|
| 35 |
+
best_scores: dict[str, float] = field(default_factory=dict)
|
| 36 |
+
|
| 37 |
+
def context(self) -> str:
|
| 38 |
+
parts = []
|
| 39 |
+
for d in self.selected:
|
| 40 |
+
content = (d.get("content") or "").strip()
|
| 41 |
+
if not content:
|
| 42 |
+
continue
|
| 43 |
+
md = d.get("metadata") or {}
|
| 44 |
+
label = md.get("path") or "chunk"
|
| 45 |
+
if md.get("library"):
|
| 46 |
+
label = f"Course notes: {md.get('label') or label}"
|
| 47 |
+
# Most course PDFs are one long page: a page number would only add noise there.
|
| 48 |
+
if md.get("page") and int(md.get("pages") or 2) > 1:
|
| 49 |
+
label += f", page {md['page']}"
|
| 50 |
+
if md.get("is_primary_authority"):
|
| 51 |
+
label += " (main source)"
|
| 52 |
+
parts.append(f"[{label}]\n{content[:1200]}")
|
| 53 |
+
return "\n\n".join(parts)
|
| 54 |
+
|
| 55 |
+
def source_documents(self) -> list[dict]:
|
| 56 |
+
return [{k: v for k, v in d.items() if k != "_score"} for d in self.selected]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _search_chunks(
|
| 60 |
+
col, space: str, q_emb: list[float], where: dict | None, allowed: set[str], n_results: int
|
| 61 |
+
) -> list[dict]:
|
| 62 |
+
"""
|
| 63 |
+
Best stored chunks matching `where` (None = whole collection), kept only if their file is still
|
| 64 |
+
in the folder tree (`allowed`), scored as cosine similarity with a small boost for main-source files.
|
| 65 |
+
"""
|
| 66 |
+
res = col.query(
|
| 67 |
+
query_embeddings=[q_emb],
|
| 68 |
+
n_results=n_results,
|
| 69 |
+
include=["documents", "metadatas", "distances"],
|
| 70 |
+
**({"where": where} if where else {}),
|
| 71 |
+
)
|
| 72 |
+
ids = (res.get("ids") or [[]])[0] or []
|
| 73 |
+
docs = (res.get("documents") or [[]])[0] or []
|
| 74 |
+
metas = (res.get("metadatas") or [[]])[0] or []
|
| 75 |
+
dists = (res.get("distances") or [[]])[0] or []
|
| 76 |
+
out = []
|
| 77 |
+
for i, cid in enumerate(ids):
|
| 78 |
+
content = (docs[i] if i < len(docs) else "") or ""
|
| 79 |
+
md = metas[i] if i < len(metas) and isinstance(metas[i], dict) else {}
|
| 80 |
+
if not content.strip() or md.get("path") not in allowed:
|
| 81 |
+
continue
|
| 82 |
+
dist = float(dists[i]) if i < len(dists) and dists[i] is not None else 2.0
|
| 83 |
+
score = distance_to_similarity(dist, space)
|
| 84 |
+
if md.get("is_primary_authority"):
|
| 85 |
+
score += MAIN_SOURCE_BOOST
|
| 86 |
+
out.append({"id": cid, "content": content, "metadata": md, "_score": score})
|
| 87 |
+
out.sort(key=lambda d: d["_score"], reverse=True)
|
| 88 |
+
return out
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _search_chat_uploads(ephemeral: list[dict], q_vec: np.ndarray) -> list[dict]:
|
| 92 |
+
"""Top 3 chunks per chat-uploaded file, scored as cosine similarity."""
|
| 93 |
+
out: list[dict] = []
|
| 94 |
+
for i, it in enumerate(ephemeral):
|
| 95 |
+
chunks = it.get("chunks") or []
|
| 96 |
+
embs = it.get("embeddings")
|
| 97 |
+
if not chunks or embs is None or len(embs) != len(chunks):
|
| 98 |
+
continue
|
| 99 |
+
scores = embs @ q_vec
|
| 100 |
+
for j, idx in enumerate(np.argsort(-scores)[:3]):
|
| 101 |
+
out.append({
|
| 102 |
+
"id": f"ephemeral|{i}|{j}",
|
| 103 |
+
"content": chunks[int(idx)],
|
| 104 |
+
"metadata": {
|
| 105 |
+
"path": f"[chat-upload] {it.get('name') or 'file'}",
|
| 106 |
+
"source_file": it.get("name") or "chat-upload",
|
| 107 |
+
"ephemeral_chat_upload": 1,
|
| 108 |
+
},
|
| 109 |
+
"_score": float(scores[int(idx)]),
|
| 110 |
+
})
|
| 111 |
+
out.sort(key=lambda d: d["_score"], reverse=True)
|
| 112 |
+
return out
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _closest(docs: list[dict]) -> list[dict]:
|
| 116 |
+
"""The best excerpts of a stage: those scoring close to its top match, at most MAX_SELECTED."""
|
| 117 |
+
if not docs:
|
| 118 |
+
return []
|
| 119 |
+
floor = docs[0]["_score"] - SOURCE_SCORE_WINDOW
|
| 120 |
+
return [d for d in docs if d["_score"] >= floor][:MAX_SELECTED]
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def course_of(opened: str, course_path: str) -> str:
|
| 124 |
+
course = course_path or ""
|
| 125 |
+
if not course and opened:
|
| 126 |
+
course = opened.split("/", 1)[0] if "/" in opened else opened
|
| 127 |
+
return course.split("/", 1)[0] if course else ""
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def find_context(
|
| 131 |
+
user_id: str,
|
| 132 |
+
question: str,
|
| 133 |
+
all_paths: list[str],
|
| 134 |
+
opened: str,
|
| 135 |
+
course: str,
|
| 136 |
+
ephemeral: list[dict],
|
| 137 |
+
include_other_notes: bool = True,
|
| 138 |
+
library_path: str = "",
|
| 139 |
+
) -> SearchResult:
|
| 140 |
+
col = get_user_collection(user_id)
|
| 141 |
+
space = collection_distance_space(col)
|
| 142 |
+
q_vec = np.asarray(embed_texts([question])[0], dtype=np.float32)
|
| 143 |
+
q_emb = q_vec.tolist()
|
| 144 |
+
all_set = set(all_paths)
|
| 145 |
+
|
| 146 |
+
eph_docs = _search_chat_uploads(ephemeral, q_vec)
|
| 147 |
+
open_docs = _search_chunks(col, space, q_emb, {"path": opened}, all_set, 6) if opened in all_set else []
|
| 148 |
+
|
| 149 |
+
# Shared course library: the open course PDF and the other PDFs of the same course, ranked
|
| 150 |
+
# together with a small lead for the open PDF, so a lecture that clearly answers the question
|
| 151 |
+
# wins over a loosely related open PDF (course notes on one subject all score fairly high).
|
| 152 |
+
lib_file_docs: list[dict] = []
|
| 153 |
+
lib_subject_docs: list[dict] = []
|
| 154 |
+
lib_file, lib_subject = library.scope_of(library_path)
|
| 155 |
+
if lib_file:
|
| 156 |
+
lib_file_docs = library.search(q_emb, {"path": lib_file}, 6)
|
| 157 |
+
if lib_subject and (include_other_notes or not lib_file):
|
| 158 |
+
subject_where = {"subject": lib_subject}
|
| 159 |
+
if lib_file:
|
| 160 |
+
subject_where = {"$and": [subject_where, {"path": {"$ne": lib_file}}]}
|
| 161 |
+
lib_subject_docs = library.search(q_emb, subject_where, 24)[:MAX_SELECTED]
|
| 162 |
+
lib_docs = sorted(
|
| 163 |
+
[{**d, "_score": d["_score"] + OPEN_LIBRARY_FILE_LEAD} for d in lib_file_docs] + lib_subject_docs,
|
| 164 |
+
key=lambda d: d["_score"],
|
| 165 |
+
reverse=True,
|
| 166 |
+
)
|
| 167 |
+
from_open_pdf = bool(lib_docs) and lib_docs[0]["metadata"].get("path") == lib_file
|
| 168 |
+
lib_stage = "library_file" if from_open_pdf else "library_subject"
|
| 169 |
+
lib_min = MIN_SCORE_LIBRARY_FILE if from_open_pdf else MIN_SCORE_LIBRARY_SUBJECT
|
| 170 |
+
|
| 171 |
+
# Course and "everything else" are selected with metadata filters (few predicates, no huge
|
| 172 |
+
# path lists), then checked against the tree so deleted files never show up.
|
| 173 |
+
course_docs: list[dict] = []
|
| 174 |
+
other_docs: list[dict] = []
|
| 175 |
+
if include_other_notes and all_paths:
|
| 176 |
+
not_opened = {"path": {"$ne": opened}} if opened else None
|
| 177 |
+
if course:
|
| 178 |
+
course_where = {"$and": [{"course_id": course}, not_opened]} if not_opened else {"course_id": course}
|
| 179 |
+
course_docs = _search_chunks(col, space, q_emb, course_where, all_set, 24)[:MAX_SELECTED]
|
| 180 |
+
other_where = {"course_id": {"$ne": course}}
|
| 181 |
+
else:
|
| 182 |
+
other_where = not_opened
|
| 183 |
+
other_docs = _search_chunks(col, space, q_emb, other_where, all_set, 24)[:MAX_SELECTED]
|
| 184 |
+
|
| 185 |
+
stages = [
|
| 186 |
+
("ephemeral", eph_docs, MIN_SCORE_CHAT_UPLOAD),
|
| 187 |
+
(lib_stage, lib_docs, lib_min),
|
| 188 |
+
("opened", open_docs, MIN_SCORE_OPEN_FILE),
|
| 189 |
+
("course", course_docs, MIN_SCORE_COURSE),
|
| 190 |
+
("all_notes", other_docs, MIN_SCORE_ALL_NOTES),
|
| 191 |
+
]
|
| 192 |
+
scored = [*stages, ("library_file", lib_file_docs, 0), ("library_subject", lib_subject_docs, 0)]
|
| 193 |
+
result = SearchResult(
|
| 194 |
+
best_scores={name: (round(docs[0]["_score"], 4) if docs else -1.0) for name, docs, _ in scored}
|
| 195 |
+
)
|
| 196 |
+
# Use the highest-priority stage that is relevant enough; otherwise the best-scoring one.
|
| 197 |
+
for name, docs, min_score in stages:
|
| 198 |
+
if docs and docs[0]["_score"] >= min_score:
|
| 199 |
+
result.stage, result.selected = name, _closest(docs)
|
| 200 |
+
return result
|
| 201 |
+
# A question about a course PDF never falls back to loosely related notes of the student's own
|
| 202 |
+
# (e.g. sample physics notes for a maths course): only the course library itself.
|
| 203 |
+
fallback = [(lib_stage, lib_docs, lib_min)] if lib_subject else stages
|
| 204 |
+
available = [(name, docs) for name, docs, _ in fallback if docs]
|
| 205 |
+
if available:
|
| 206 |
+
result.stage, docs = max(available, key=lambda s: s[1][0]["_score"])
|
| 207 |
+
result.selected = _closest(docs)
|
| 208 |
+
return result
|
| 209 |
+
|
backend/settings.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Settings read from the environment, plus request limits and thresholds in one place."""
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def _env_str(name: str, default: str) -> str:
|
| 6 |
+
return (os.getenv(name) or default).strip() or default
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _env_float(name: str, default: float) -> float:
|
| 10 |
+
try:
|
| 11 |
+
return float(_env_str(name, str(default)))
|
| 12 |
+
except ValueError:
|
| 13 |
+
return default
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
MAX_UPLOAD_MB = _env_float("MAX_UPLOAD_MB", 20)
|
| 17 |
+
MAX_UPLOAD_BYTES = int(MAX_UPLOAD_MB * 1024 * 1024)
|
| 18 |
+
MAX_ACTIVE_UPLOADS_PER_USER = 10 # queued + processing; each holds the file in memory until done
|
| 19 |
+
CHAT_CACHE_TTL_SECONDS = int(_env_float("CHAT_CACHE_TTL_SECONDS", 7200))
|
| 20 |
+
MAX_CHAT_UPLOAD_CHARS = int(_env_float("MAX_CHAT_UPLOAD_CHARS", 300000))
|
| 21 |
+
MAX_CHAT_FILES_PER_SESSION = 10
|
| 22 |
+
MAX_EDITED_TEXT_CHARS = 500000
|
| 23 |
+
|
| 24 |
+
# Minimum cosine similarity for a source to count as relevant. Every stage uses the same 0..1 scale.
|
| 25 |
+
MIN_SCORE_CHAT_UPLOAD = 0.30
|
| 26 |
+
MIN_SCORE_OPEN_FILE = 0.20
|
| 27 |
+
MIN_SCORE_COURSE = 0.25
|
| 28 |
+
MIN_SCORE_ALL_NOTES = 0.25
|
| 29 |
+
MAIN_SOURCE_BOOST = 0.03 # small ranking boost for files the student marked as their main source
|
| 30 |
+
SOURCE_SCORE_WINDOW = 0.2 # keep excerpts scoring within this much of the best one (drops loosely related files)
|
| 31 |
+
|
| 32 |
+
# Request limits as (max requests, window seconds). Per-IP limits are generous because a whole
|
| 33 |
+
# campus can share one public IP; the per-email login limit is what stops password guessing.
|
| 34 |
+
LIMIT_REGISTER_PER_IP = (50, 3600)
|
| 35 |
+
LIMIT_LOGIN_PER_IP = (200, 900)
|
| 36 |
+
LIMIT_LOGIN_PER_EMAIL = (10, 900)
|
| 37 |
+
LIMIT_PASSWORD_CHECK_PER_USER = (10, 900) # change password / delete account
|
| 38 |
+
LIMIT_FORGOT_PER_IP = (20, 3600)
|
| 39 |
+
LIMIT_FORGOT_PER_EMAIL = (3, 3600)
|
| 40 |
+
LIMIT_GUEST_ID_PER_IP = (100, 3600)
|
| 41 |
+
LIMIT_UPLOADS_PER_USER = (30, 600)
|
| 42 |
+
LIMIT_QUESTIONS_PER_USER = (60, 600)
|
| 43 |
+
LIMIT_STUDY_PER_USER = (20, 600)
|
| 44 |
+
LIMIT_ONENOTE_SYNC_PER_USER = (5, 600)
|
| 45 |
+
LIMIT_ONENOTE_CONNECT_PER_USER = (10, 600)
|
| 46 |
+
LIMIT_RESET_PER_IP = (20, 3600) # using password-reset links
|
| 47 |
+
LIMIT_TREE_CHANGES_PER_USER = (120, 60) # create, move, rename, delete, main-source marking
|
| 48 |
+
LIMIT_TEXT_EDITS_PER_USER = (60, 600) # saving edited text (re-processes the file for search)
|
| 49 |
+
LIMIT_DECK_CHANGES_PER_USER = (60, 600) # creating and deleting flashcard decks
|
| 50 |
+
LIMIT_DELETE_ALL_PER_USER = (5, 3600) # "delete all my notes"
|
| 51 |
+
|
| 52 |
+
# Overall caps on every request (checked before any route), on top of the per-route limits above.
|
| 53 |
+
LIMIT_ALL_PER_IP = (1200, 60) # one network address (a campus may share one)
|
| 54 |
+
LIMIT_ALL_PER_SESSION = (300, 60) # one signed-in browser
|
| 55 |
+
UNLIMITED_PATHS = ("/health",) # monitoring checks are never limited
|
| 56 |
+
|
| 57 |
+
# Daily caps on paid AI use per user (cost control): uploads read by Sarvam Vision, questions and
|
| 58 |
+
# study tools answered by Sarvam chat models.
|
| 59 |
+
LIMIT_UPLOADS_PER_DAY = (200, 86400)
|
| 60 |
+
LIMIT_QUESTIONS_PER_DAY = (300, 86400)
|
| 61 |
+
LIMIT_STUDY_PER_DAY = (100, 86400)
|
| 62 |
+
|
| 63 |
+
MIN_PASSWORD_LEN = 8
|
| 64 |
+
MAX_PASSWORD_BYTES = 72 # bcrypt ignores anything after 72 bytes
|
| 65 |
+
|
| 66 |
+
FRONTEND_URL = _env_str("FRONTEND_URL", "https://cherie-dips.github.io/NoteScanner/")
|
| 67 |
+
|
| 68 |
+
DEFAULT_CORS_ORIGINS = (
|
| 69 |
+
"http://localhost:5173",
|
| 70 |
+
"http://127.0.0.1:5173",
|
| 71 |
+
"http://localhost:4173",
|
| 72 |
+
"https://cherie-dips.github.io",
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def allowed_origins() -> list[str]:
|
| 77 |
+
"""Websites allowed to call this API (CORS_ORIGINS env, comma-separated)."""
|
| 78 |
+
raw = (os.getenv("CORS_ORIGINS") or "").strip()
|
| 79 |
+
if not raw:
|
| 80 |
+
return list(DEFAULT_CORS_ORIGINS)
|
| 81 |
+
return [o.strip().rstrip("/") for o in raw.split(",") if o.strip()]
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _env_bool(name: str, default: bool) -> bool:
|
| 85 |
+
return _env_str(name, "true" if default else "false").lower() in ("1", "true", "yes", "on")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ---------- Shared course library (read once on the server, searched by every student) ----------
|
| 89 |
+
# The PDFs behind SDE-Prep's Notes tab: a public Supabase Storage bucket. The key is that project's
|
| 90 |
+
# publishable anon key, already served in plain text by SDE-Prep (js/notes-data.js); it can only
|
| 91 |
+
# read the bucket. Never put a service_role key here.
|
| 92 |
+
LIBRARY_ENABLED = _env_bool("LIBRARY_ENABLED", True)
|
| 93 |
+
LIBRARY_SUPABASE_URL = _env_str("LIBRARY_SUPABASE_URL", "https://jlmzxsaysnvoxbutfkxw.supabase.co").rstrip("/")
|
| 94 |
+
LIBRARY_SUPABASE_KEY = _env_str(
|
| 95 |
+
"LIBRARY_SUPABASE_KEY",
|
| 96 |
+
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpsbXp4c2F5c252b3hidXRma3h3Iiwicm9sZSI6"
|
| 97 |
+
"ImFub24iLCJpYXQiOjE3NzIwNDA2NTcsImV4cCI6MjA4NzYxNjY1N30.VvBgtpcmwuhoBSdjUKE5A3_9At-S2cCznCqfS_ECUkg",
|
| 98 |
+
)
|
| 99 |
+
LIBRARY_BUCKET = _env_str("LIBRARY_BUCKET", "Notes")
|
| 100 |
+
# Top-level folders of the bucket to index (comma-separated). SDE-Prep shows only this category.
|
| 101 |
+
LIBRARY_PREFIXES = tuple(
|
| 102 |
+
p.strip().strip("/") for p in _env_str("LIBRARY_PREFIXES", "plaksha-university").split(",") if p.strip()
|
| 103 |
+
)
|
| 104 |
+
# How handwritten and scanned pages are read: auto (Sarvam Vision when SARVAM_API_KEY is set, else
|
| 105 |
+
# Tesseract), sarvam, tesseract, or off (only pages that already contain text).
|
| 106 |
+
LIBRARY_OCR = _env_str("LIBRARY_OCR", "auto").lower()
|
| 107 |
+
# Check the bucket for new or changed PDFs every N hours. 0 = only when started by hand
|
| 108 |
+
# (scripts/index_library.py or the admin endpoint), because reading pages with Sarvam costs money.
|
| 109 |
+
LIBRARY_SYNC_HOURS = _env_float("LIBRARY_SYNC_HOURS", 0)
|
| 110 |
+
MIN_SCORE_LIBRARY_FILE = 0.20 # the course PDF the student has open (same bar as an open file)
|
| 111 |
+
MIN_SCORE_LIBRARY_SUBJECT = 0.25 # the other PDFs of that course
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# ---------- Running a pilot ----------
|
| 115 |
+
APP_TIMEZONE = _env_str("APP_TIMEZONE", "Asia/Kolkata") # "today", streaks and reminder times use this
|
| 116 |
+
STARTER_NOTES = _env_bool("STARTER_NOTES", True) # new accounts get a "Getting started" folder
|
| 117 |
+
PRIVACY_VERSION = "2026-10" # bump when the privacy note changes
|
| 118 |
+
ADMIN_EMAILS = {e.strip().lower() for e in (os.getenv("ADMIN_EMAILS") or "").split(",") if e.strip()}
|
| 119 |
+
ALERT_WEBHOOK_URL = (os.getenv("ALERT_WEBHOOK_URL") or "").strip() # Slack/Discord-style webhook for errors
|
| 120 |
+
|
| 121 |
+
# AI cost estimate. Prices are 0 (unknown) until you set them from your Sarvam plan.
|
| 122 |
+
AI_PRICE_PER_PAGE = _env_float("AI_PRICE_PER_PAGE", 0) # Sarvam Vision, per page read
|
| 123 |
+
AI_PRICE_PER_1K_INPUT_TOKENS = _env_float("AI_PRICE_PER_1K_INPUT_TOKENS", 0)
|
| 124 |
+
AI_PRICE_PER_1K_OUTPUT_TOKENS = _env_float("AI_PRICE_PER_1K_OUTPUT_TOKENS", 0)
|
| 125 |
+
AI_PRICE_CURRENCY = _env_str("AI_PRICE_CURRENCY", "INR")
|
| 126 |
+
AI_MONTHLY_BUDGET = _env_float("AI_MONTHLY_BUDGET", 0) # 0 = no budget; otherwise paid AI pauses when reached
|
| 127 |
+
|
| 128 |
+
# Daily review reminder emails (only when SMTP is set up and the student turned them on).
|
| 129 |
+
REMINDERS_ENABLED = _env_bool("REMINDERS_ENABLED", True)
|
| 130 |
+
REMINDER_HOUR = int(_env_float("REMINDER_HOUR", 8)) # local hour (APP_TIMEZONE) after which reminders go out
|
| 131 |
+
|
| 132 |
+
ANSWER_LANGUAGES = (
|
| 133 |
+
"English", "Hindi", "Bengali", "Gujarati", "Kannada", "Malayalam",
|
| 134 |
+
"Marathi", "Odia", "Punjabi", "Tamil", "Telugu",
|
| 135 |
+
)
|
backend/starter_notes.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Notes every new account starts with, so a new student can try asking a question right away."""
|
| 2 |
+
import logging
|
| 3 |
+
import threading
|
| 4 |
+
|
| 5 |
+
logger = logging.getLogger(__name__)
|
| 6 |
+
|
| 7 |
+
STARTER_FOLDER = "Getting started"
|
| 8 |
+
|
| 9 |
+
WELCOME = """# Welcome to NoteScanner
|
| 10 |
+
|
| 11 |
+
NoteScanner turns your course notes into a study assistant. This folder is just an example;
|
| 12 |
+
delete it whenever you like.
|
| 13 |
+
|
| 14 |
+
## How to use it
|
| 15 |
+
|
| 16 |
+
1. **Upload your notes.** Use the upload button at the top of the file list, or drag files onto a
|
| 17 |
+
folder. PDFs, photos of handwritten pages and text files all work. Make one folder per course.
|
| 18 |
+
2. **Ask questions.** Type in the chat on the right. Answers come from your own notes first, and
|
| 19 |
+
each answer lists the notes it used; click one to open it.
|
| 20 |
+
3. **Make flashcards and practice questions.** Open a file, then use Flashcards, Mock MCQ or Summary.
|
| 21 |
+
4. **Review a little every day.** Save flashcards as a deck. The Review tab shows the cards that are
|
| 22 |
+
due today, so you revise each card just before you'd forget it.
|
| 23 |
+
|
| 24 |
+
## Tips
|
| 25 |
+
|
| 26 |
+
- If a scanned page was read wrongly, open the file, switch to Text view and fix it.
|
| 27 |
+
- Mark your most reliable file in a course as the "main source" (right-click it).
|
| 28 |
+
- Try asking: "What is Newton's second law?" or "Explain momentum with an example."
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
SAMPLE_PHYSICS = """# Newton's laws of motion (sample notes)
|
| 32 |
+
|
| 33 |
+
## First law (inertia)
|
| 34 |
+
An object stays at rest, or keeps moving in a straight line at constant speed, unless a net
|
| 35 |
+
external force acts on it. Mass is a measure of an object's inertia.
|
| 36 |
+
|
| 37 |
+
## Second law
|
| 38 |
+
The net force on an object equals its mass times its acceleration: $F = ma$.
|
| 39 |
+
Force is measured in newtons (N), where 1 N = 1 kg·m/s².
|
| 40 |
+
|
| 41 |
+
## Third law
|
| 42 |
+
For every action there is an equal and opposite reaction: if body A pushes body B, then B pushes A
|
| 43 |
+
with a force of the same size in the opposite direction.
|
| 44 |
+
|
| 45 |
+
## Momentum
|
| 46 |
+
Momentum is mass times velocity: $p = mv$. Newton's second law can also be written as
|
| 47 |
+
$F = \\frac{dp}{dt}$. In a closed system with no external force, total momentum is conserved.
|
| 48 |
+
|
| 49 |
+
## Worked example
|
| 50 |
+
A 2 kg cart accelerates at 3 m/s². The net force on it is 2 × 3 = 6 N.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
STARTER_FILES = (
|
| 54 |
+
("Welcome to NoteScanner.md", WELCOME),
|
| 55 |
+
("Sample - Newton's laws of motion.md", SAMPLE_PHYSICS),
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
# The name the student signed up under: "Study AI" is NoteScanner inside SDE-Prep's Study AI tab.
|
| 59 |
+
APP_NAMES = ("NoteScanner", "Study AI")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def starter_files(app_name: str = "NoteScanner") -> tuple[tuple[str, str], ...]:
|
| 63 |
+
app = app_name if app_name in APP_NAMES else "NoteScanner"
|
| 64 |
+
if app == "NoteScanner":
|
| 65 |
+
return STARTER_FILES
|
| 66 |
+
return ((f"Welcome to {app}.md", WELCOME.replace("NoteScanner", app)), *STARTER_FILES[1:])
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def add_starter_notes(user_id: str, app_name: str = "NoteScanner") -> None:
|
| 70 |
+
"""Save the starter files for a new account (no AI calls; only local embeddings)."""
|
| 71 |
+
from backend.uploads import save_note_text
|
| 72 |
+
|
| 73 |
+
for name, text in starter_files(app_name):
|
| 74 |
+
try:
|
| 75 |
+
save_note_text(user_id, STARTER_FOLDER, name, text)
|
| 76 |
+
except Exception:
|
| 77 |
+
logger.exception("Could not add starter note %s for %s", name, user_id)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def add_starter_notes_in_background(user_id: str, app_name: str = "NoteScanner") -> None:
|
| 81 |
+
threading.Thread(
|
| 82 |
+
target=add_starter_notes, args=(user_id, app_name), name="starter-notes", daemon=True
|
| 83 |
+
).start()
|
backend/study_store.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Saved flashcard decks with spaced repetition, stored per user in `user_{user_id}_study`.
|
| 3 |
+
|
| 4 |
+
Each deck and each card is one small record. A card's schedule lives in its metadata
|
| 5 |
+
(due_at, interval_days, ease, reps, lapses) so "what's due" is a simple metadata filter.
|
| 6 |
+
Scheduling is a simplified SM-2 (the algorithm behind Anki's original scheduler).
|
| 7 |
+
"""
|
| 8 |
+
import csv
|
| 9 |
+
import datetime as dt
|
| 10 |
+
import io
|
| 11 |
+
import json
|
| 12 |
+
import time
|
| 13 |
+
import uuid
|
| 14 |
+
|
| 15 |
+
from backend.chroma_store import (
|
| 16 |
+
_delete_collection,
|
| 17 |
+
_dummy_embedding,
|
| 18 |
+
_get_collection_or_none,
|
| 19 |
+
_get_or_create_collection,
|
| 20 |
+
delete_ids,
|
| 21 |
+
get_all,
|
| 22 |
+
short_id,
|
| 23 |
+
write_records,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
GRADES = ("again", "hard", "good", "easy")
|
| 27 |
+
MAX_CARDS_PER_DECK = 200
|
| 28 |
+
MAX_FIELD_CHARS = 4000 # keeps each card record well under Chroma Cloud's 16 KB document limit
|
| 29 |
+
RELEARN_SECONDS = 600 # "again" shows the card again in 10 minutes
|
| 30 |
+
DAY = 86400
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _collection(user_id: str, create: bool):
|
| 34 |
+
name = f"user_{user_id}_study"
|
| 35 |
+
return _get_or_create_collection(name) if create else _get_collection_or_none(name)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def create_deck(user_id: str, name: str, source_path: str, cards: list[dict]) -> dict:
|
| 39 |
+
col = _collection(user_id, create=True)
|
| 40 |
+
now = int(time.time())
|
| 41 |
+
deck_id = uuid.uuid4().hex[:16]
|
| 42 |
+
clean = []
|
| 43 |
+
for c in cards[:MAX_CARDS_PER_DECK]:
|
| 44 |
+
front = str(c.get("front") or "").strip()[:MAX_FIELD_CHARS]
|
| 45 |
+
back = str(c.get("back") or "").strip()[:MAX_FIELD_CHARS]
|
| 46 |
+
if front and back:
|
| 47 |
+
clean.append({"front": front, "back": back, "source": str(c.get("source") or "notes")[:40]})
|
| 48 |
+
if not clean:
|
| 49 |
+
raise ValueError("A deck needs at least one card with a front and a back.")
|
| 50 |
+
name = (name or "").strip()[:120] or "Flashcards"
|
| 51 |
+
col.add(
|
| 52 |
+
ids=[f"deck_{deck_id}"],
|
| 53 |
+
documents=[""],
|
| 54 |
+
embeddings=[_dummy_embedding()],
|
| 55 |
+
metadatas=[{
|
| 56 |
+
"kind": "deck",
|
| 57 |
+
"deck_id": deck_id,
|
| 58 |
+
"name": name,
|
| 59 |
+
"source_path": (source_path or "")[:1000],
|
| 60 |
+
"created_at": now,
|
| 61 |
+
"card_count": len(clean),
|
| 62 |
+
}],
|
| 63 |
+
)
|
| 64 |
+
card_ids = [f"card_{uuid.uuid4().hex[:20]}" for _ in clean]
|
| 65 |
+
write_records(
|
| 66 |
+
col,
|
| 67 |
+
"add",
|
| 68 |
+
card_ids,
|
| 69 |
+
documents=[json.dumps(c, ensure_ascii=False) for c in clean],
|
| 70 |
+
embeddings=[_dummy_embedding()] * len(clean),
|
| 71 |
+
metadatas=[
|
| 72 |
+
{"kind": "card", "deck_id": deck_id, "due_at": now, "interval_days": 0.0, "ease": 2.5, "reps": 0, "lapses": 0}
|
| 73 |
+
for _ in clean
|
| 74 |
+
],
|
| 75 |
+
)
|
| 76 |
+
return {"deck_id": deck_id, "name": name, "card_count": len(clean)}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def list_decks(user_id: str) -> list[dict]:
|
| 80 |
+
col = _collection(user_id, create=False)
|
| 81 |
+
if col is None:
|
| 82 |
+
return []
|
| 83 |
+
now = int(time.time())
|
| 84 |
+
decks = get_all(col, where={"kind": "deck"}, include=["metadatas"])
|
| 85 |
+
due = get_all(col, where={"$and": [{"kind": "card"}, {"due_at": {"$lte": now}}]}, include=["metadatas"])
|
| 86 |
+
due_counts: dict[str, int] = {}
|
| 87 |
+
for m in due.get("metadatas") or []:
|
| 88 |
+
did = (m or {}).get("deck_id")
|
| 89 |
+
due_counts[did] = due_counts.get(did, 0) + 1
|
| 90 |
+
out = []
|
| 91 |
+
for m in decks.get("metadatas") or []:
|
| 92 |
+
m = m or {}
|
| 93 |
+
out.append({
|
| 94 |
+
"deck_id": m.get("deck_id"),
|
| 95 |
+
"name": m.get("name") or "Flashcards",
|
| 96 |
+
"source_path": m.get("source_path") or "",
|
| 97 |
+
"card_count": int(m.get("card_count") or 0),
|
| 98 |
+
"due_count": due_counts.get(m.get("deck_id"), 0),
|
| 99 |
+
"created_at": int(m.get("created_at") or 0),
|
| 100 |
+
})
|
| 101 |
+
out.sort(key=lambda d: d["created_at"], reverse=True)
|
| 102 |
+
return out
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _deck_exists(col, deck_id: str) -> bool:
|
| 106 |
+
return bool(col.get(ids=[f"deck_{deck_id}"], include=[]).get("ids"))
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def deck_cards(user_id: str, deck_id: str, due_only: bool, limit: int) -> list[dict] | None:
|
| 110 |
+
"""Cards of a deck (None if the deck doesn't exist). due_only: cards due now, soonest first."""
|
| 111 |
+
col = _collection(user_id, create=False)
|
| 112 |
+
if col is None or not _deck_exists(col, deck_id):
|
| 113 |
+
return None
|
| 114 |
+
where: dict = {"$and": [{"kind": "card"}, {"deck_id": deck_id}]}
|
| 115 |
+
if due_only:
|
| 116 |
+
where["$and"].append({"due_at": {"$lte": int(time.time())}})
|
| 117 |
+
res = get_all(col, where=where, include=["documents", "metadatas"])
|
| 118 |
+
cards = []
|
| 119 |
+
for cid, doc, meta in zip(res["ids"], res.get("documents") or [], res.get("metadatas") or []):
|
| 120 |
+
body = json.loads(doc or "{}")
|
| 121 |
+
meta = meta or {}
|
| 122 |
+
cards.append({
|
| 123 |
+
"card_id": cid,
|
| 124 |
+
"front": body.get("front", ""),
|
| 125 |
+
"back": body.get("back", ""),
|
| 126 |
+
"source": body.get("source", "notes"),
|
| 127 |
+
"due_at": int(meta.get("due_at") or 0),
|
| 128 |
+
"interval_days": float(meta.get("interval_days") or 0),
|
| 129 |
+
"reps": int(meta.get("reps") or 0),
|
| 130 |
+
})
|
| 131 |
+
cards.sort(key=lambda c: c["due_at"])
|
| 132 |
+
return cards[: max(1, min(limit, MAX_CARDS_PER_DECK))]
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def schedule(meta: dict, grade: str, now: int) -> dict:
|
| 136 |
+
"""Next review for a card after the student grades it (simplified SM-2)."""
|
| 137 |
+
ease = float(meta.get("ease") or 2.5)
|
| 138 |
+
interval = float(meta.get("interval_days") or 0)
|
| 139 |
+
reps = int(meta.get("reps") or 0)
|
| 140 |
+
lapses = int(meta.get("lapses") or 0)
|
| 141 |
+
if grade == "again":
|
| 142 |
+
return {**meta, "ease": max(1.3, ease - 0.2), "interval_days": 0.0, "reps": 0,
|
| 143 |
+
"lapses": lapses + 1, "due_at": now + RELEARN_SECONDS}
|
| 144 |
+
if grade == "hard":
|
| 145 |
+
ease = max(1.3, ease - 0.15)
|
| 146 |
+
interval = 1.0 if reps == 0 else max(1.0, interval * 1.2)
|
| 147 |
+
elif grade == "good":
|
| 148 |
+
interval = 1.0 if reps == 0 else (3.0 if reps == 1 else interval * ease)
|
| 149 |
+
else: # easy
|
| 150 |
+
ease += 0.15
|
| 151 |
+
interval = 3.0 if reps == 0 else max(4.0, interval * ease * 1.3)
|
| 152 |
+
interval = round(min(interval, 365.0), 2)
|
| 153 |
+
return {**meta, "ease": round(ease, 3), "interval_days": interval, "reps": reps + 1,
|
| 154 |
+
"lapses": lapses, "due_at": now + int(interval * DAY)}
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def review_card(user_id: str, card_id: str, grade: str) -> dict | None:
|
| 158 |
+
if grade not in GRADES:
|
| 159 |
+
raise ValueError("Grade must be one of: again, hard, good, easy.")
|
| 160 |
+
col = _collection(user_id, create=False)
|
| 161 |
+
if col is None or not card_id.startswith("card_"):
|
| 162 |
+
return None
|
| 163 |
+
res = col.get(ids=[card_id], include=["metadatas"])
|
| 164 |
+
if not res.get("ids"):
|
| 165 |
+
return None
|
| 166 |
+
new_meta = schedule(res["metadatas"][0] or {}, grade, int(time.time()))
|
| 167 |
+
col.update(ids=[card_id], metadatas=[new_meta])
|
| 168 |
+
return {"card_id": card_id, "due_at": new_meta["due_at"], "interval_days": new_meta["interval_days"]}
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def delete_deck(user_id: str, deck_id: str) -> bool:
|
| 172 |
+
col = _collection(user_id, create=False)
|
| 173 |
+
if col is None or not _deck_exists(col, deck_id):
|
| 174 |
+
return False
|
| 175 |
+
delete_ids(col, get_all(col, where={"deck_id": deck_id}, include=[])["ids"])
|
| 176 |
+
col.delete(ids=[f"deck_{deck_id}"])
|
| 177 |
+
return True
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def export_csv(user_id: str, deck_id: str) -> tuple[str, str] | None:
|
| 181 |
+
"""(deck name, CSV text with front,back rows) for importing into Anki, or None."""
|
| 182 |
+
col = _collection(user_id, create=False)
|
| 183 |
+
if col is None:
|
| 184 |
+
return None
|
| 185 |
+
deck = col.get(ids=[f"deck_{deck_id}"], include=["metadatas"])
|
| 186 |
+
if not deck.get("ids"):
|
| 187 |
+
return None
|
| 188 |
+
cards = deck_cards(user_id, deck_id, due_only=False, limit=MAX_CARDS_PER_DECK) or []
|
| 189 |
+
buf = io.StringIO()
|
| 190 |
+
writer = csv.writer(buf)
|
| 191 |
+
for c in cards:
|
| 192 |
+
writer.writerow([c["front"], c["back"]])
|
| 193 |
+
return (deck["metadatas"][0] or {}).get("name") or "flashcards", buf.getvalue()
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def delete_all(user_id: str) -> None:
|
| 197 |
+
_delete_collection(f"user_{user_id}_study")
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def due_count(user_id: str, until: int | None = None) -> int:
|
| 201 |
+
"""Number of cards due by `until` (epoch seconds; default now) across all decks."""
|
| 202 |
+
col = _collection(user_id, create=False)
|
| 203 |
+
if col is None:
|
| 204 |
+
return 0
|
| 205 |
+
until = int(until if until is not None else time.time())
|
| 206 |
+
return len(get_all(col, where={"$and": [{"kind": "card"}, {"due_at": {"$lte": until}}]}, include=[])["ids"])
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
# ---------- Quiz results per file (for "weak topics") ----------
|
| 210 |
+
def mcq_record(user_id: str, path: str, correct: int, total: int) -> dict:
|
| 211 |
+
col = _collection(user_id, create=True)
|
| 212 |
+
rid = short_id("mcq_", path)
|
| 213 |
+
res = col.get(ids=[rid], include=["metadatas"])
|
| 214 |
+
meta = dict((res.get("metadatas") or [{}])[0] or {}) if res.get("ids") else {"kind": "mcqstat", "path": path[:1000]}
|
| 215 |
+
meta["correct"] = int(meta.get("correct") or 0) + int(correct)
|
| 216 |
+
meta["total"] = int(meta.get("total") or 0) + int(total)
|
| 217 |
+
meta["updated_at"] = int(time.time())
|
| 218 |
+
col.upsert(ids=[rid], documents=[""], embeddings=[_dummy_embedding()], metadatas=[meta])
|
| 219 |
+
return meta
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def weak_topics(user_id: str, min_answered: int = 3, below: float = 0.7, limit: int = 5) -> list[dict]:
|
| 223 |
+
"""Files whose quiz accuracy is lowest (only files with at least `min_answered` answers)."""
|
| 224 |
+
col = _collection(user_id, create=False)
|
| 225 |
+
if col is None:
|
| 226 |
+
return []
|
| 227 |
+
out = []
|
| 228 |
+
for m in get_all(col, where={"kind": "mcqstat"}, include=["metadatas"]).get("metadatas") or []:
|
| 229 |
+
total, correct = int((m or {}).get("total") or 0), int((m or {}).get("correct") or 0)
|
| 230 |
+
if total >= min_answered and correct / total < below:
|
| 231 |
+
out.append({"path": m.get("path") or "", "correct": correct, "total": total, "accuracy": round(correct / total, 3)})
|
| 232 |
+
out.sort(key=lambda t: (t["accuracy"], -t["total"]))
|
| 233 |
+
return out[:limit]
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
# ---------- Exam plans ----------
|
| 237 |
+
def build_exam_plan(files: list[str], exam_day: dt.date, today: dt.date) -> list[dict]:
|
| 238 |
+
"""
|
| 239 |
+
A day-by-day plan from today to the exam: spread the course files over the revision days
|
| 240 |
+
(a second pass if there's time), a timed mock test the day before, light review on exam day.
|
| 241 |
+
"""
|
| 242 |
+
days_left = (exam_day - today).days
|
| 243 |
+
if days_left < 0:
|
| 244 |
+
raise ValueError("The exam date is in the past.")
|
| 245 |
+
if days_left > 180:
|
| 246 |
+
raise ValueError("Pick an exam date within the next 6 months.")
|
| 247 |
+
names = [f.rsplit("/", 1)[-1] for f in files]
|
| 248 |
+
if days_left == 0:
|
| 249 |
+
return [{"date": today.isoformat(), "tasks": ["Exam today: review your due flashcards and skim your main-source notes. Good luck!"]}]
|
| 250 |
+
|
| 251 |
+
study_days = [today + dt.timedelta(days=d) for d in range(days_left)]
|
| 252 |
+
mock_day = study_days[-1] if days_left >= 2 else None
|
| 253 |
+
revision_days = study_days[:-1] if mock_day else study_days
|
| 254 |
+
n = len(revision_days)
|
| 255 |
+
groups: list[list[str]] = [[] for _ in range(n)]
|
| 256 |
+
if names:
|
| 257 |
+
if len(names) >= n:
|
| 258 |
+
for i, name in enumerate(names):
|
| 259 |
+
groups[i * n // len(names)].append(name)
|
| 260 |
+
else:
|
| 261 |
+
for i in range(n):
|
| 262 |
+
groups[i].append(names[i % len(names)])
|
| 263 |
+
|
| 264 |
+
plan = []
|
| 265 |
+
for i, day in enumerate(revision_days):
|
| 266 |
+
tasks = []
|
| 267 |
+
if groups[i]:
|
| 268 |
+
again = names and len(names) < n and i >= len(names)
|
| 269 |
+
tasks.append(("Revise again: " if again else "Revise: ") + ", ".join(groups[i]) + " (ask about anything unclear)")
|
| 270 |
+
tasks.append("Make flashcards for what you revised, and review the cards due today")
|
| 271 |
+
if i and i % 3 == 0:
|
| 272 |
+
tasks.append("Practice quiz (Mock MCQ) on the files from the last few days")
|
| 273 |
+
plan.append({"date": day.isoformat(), "tasks": tasks})
|
| 274 |
+
if mock_day:
|
| 275 |
+
plan.append({
|
| 276 |
+
"date": mock_day.isoformat(),
|
| 277 |
+
"tasks": ["Timed mock test for the whole course (Exam tab)", "Go over the questions you got wrong and re-read those files"],
|
| 278 |
+
})
|
| 279 |
+
plan.append({"date": exam_day.isoformat(), "tasks": ["Exam day: review only your due flashcards. Good luck!"]})
|
| 280 |
+
return plan
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def _exam_public(meta: dict, plan: list[dict], today: dt.date) -> dict:
|
| 284 |
+
exam_day = dt.date.fromisoformat(meta["exam_date"])
|
| 285 |
+
return {
|
| 286 |
+
"exam_id": meta["exam_id"],
|
| 287 |
+
"course": meta.get("course") or "",
|
| 288 |
+
"exam_date": meta["exam_date"],
|
| 289 |
+
"days_left": (exam_day - today).days,
|
| 290 |
+
"plan": plan,
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def save_exam(user_id: str, course: str, files: list[str], exam_day: dt.date, today: dt.date) -> dict:
|
| 295 |
+
plan = build_exam_plan(files, exam_day, today)
|
| 296 |
+
col = _collection(user_id, create=True)
|
| 297 |
+
exam_id = uuid.uuid4().hex[:16]
|
| 298 |
+
meta = {
|
| 299 |
+
"kind": "exam",
|
| 300 |
+
"exam_id": exam_id,
|
| 301 |
+
"course": course[:500],
|
| 302 |
+
"exam_date": exam_day.isoformat(),
|
| 303 |
+
"exam_day_num": exam_day.year * 10000 + exam_day.month * 100 + exam_day.day,
|
| 304 |
+
"created_at": int(time.time()),
|
| 305 |
+
}
|
| 306 |
+
doc = json.dumps(plan, ensure_ascii=False)
|
| 307 |
+
if len(doc.encode("utf-8")) > 15000: # keep within one Chroma Cloud document
|
| 308 |
+
raise ValueError("That plan is too long to save. Pick a closer exam date or a smaller folder.")
|
| 309 |
+
col.add(ids=[f"exam_{exam_id}"], documents=[doc], embeddings=[_dummy_embedding()], metadatas=[meta])
|
| 310 |
+
return _exam_public(meta, plan, today)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def list_exams(user_id: str, today: dt.date) -> list[dict]:
|
| 314 |
+
col = _collection(user_id, create=False)
|
| 315 |
+
if col is None:
|
| 316 |
+
return []
|
| 317 |
+
res = get_all(col, where={"kind": "exam"}, include=["documents", "metadatas"])
|
| 318 |
+
exams = [_exam_public(m or {}, json.loads(d or "[]"), today) for d, m in zip(res.get("documents") or [], res.get("metadatas") or [])]
|
| 319 |
+
exams.sort(key=lambda e: e["exam_date"])
|
| 320 |
+
return exams
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def delete_exam(user_id: str, exam_id: str) -> bool:
|
| 324 |
+
col = _collection(user_id, create=False)
|
| 325 |
+
if col is None or not col.get(ids=[f"exam_{exam_id}"], include=[]).get("ids"):
|
| 326 |
+
return False
|
| 327 |
+
col.delete(ids=[f"exam_{exam_id}"])
|
| 328 |
+
return True
|
backend/uploads.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Reading text out of uploaded files, and the background queue that processes note uploads.
|
| 3 |
+
|
| 4 |
+
Reading a PDF or photo with Sarvam Vision can take minutes, so /upload_note only checks the file
|
| 5 |
+
and queues it. A worker thread reads the text, saves it for search, and only then adds the file
|
| 6 |
+
to the user's folder tree. The browser polls /jobs/{job_id} to show progress.
|
| 7 |
+
"""
|
| 8 |
+
import logging
|
| 9 |
+
import os
|
| 10 |
+
import threading
|
| 11 |
+
import time
|
| 12 |
+
import uuid
|
| 13 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 14 |
+
from dataclasses import dataclass
|
| 15 |
+
|
| 16 |
+
from fastapi import HTTPException, UploadFile
|
| 17 |
+
|
| 18 |
+
from backend import alerts, llm_pipeline, usage
|
| 19 |
+
from backend.chroma_store import user_document_upsert, user_lock, vfs_set_tree
|
| 20 |
+
from backend.extract_api import extract_text_from_image_bytes
|
| 21 |
+
from backend.ingest_api import ingest_text_for_path
|
| 22 |
+
from backend.pages import PageStarts, anchor_page_starts, join_pages, pdf_page_texts
|
| 23 |
+
from backend.paths import get_vfs_tree_clean
|
| 24 |
+
from backend.settings import MAX_ACTIVE_UPLOADS_PER_USER, MAX_UPLOAD_BYTES, MAX_UPLOAD_MB
|
| 25 |
+
from backend.vfs_tree import tree_add_file
|
| 26 |
+
|
| 27 |
+
logger = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
IMAGE_MIME_TYPES = {
|
| 30 |
+
".jpg": "image/jpeg",
|
| 31 |
+
".jpeg": "image/jpeg",
|
| 32 |
+
".png": "image/png",
|
| 33 |
+
".webp": "image/webp",
|
| 34 |
+
".gif": "image/gif",
|
| 35 |
+
".bmp": "image/bmp",
|
| 36 |
+
".tiff": "image/tiff",
|
| 37 |
+
}
|
| 38 |
+
PLAIN_TEXT_EXTS = (".txt", ".md", ".csv", ".json", ".log")
|
| 39 |
+
JOB_KEEP_SECONDS = 3600
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class ExtractionError(Exception):
|
| 43 |
+
"""No text could be read from the file; the message is shown to the user."""
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def clean_upload_name(file: UploadFile) -> str:
|
| 47 |
+
raw_name = (file.filename or "upload").replace("\\", "/").split("/")[-1].strip()
|
| 48 |
+
if not raw_name or ".." in raw_name:
|
| 49 |
+
raise HTTPException(status_code=400, detail="Invalid file name.")
|
| 50 |
+
return raw_name
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def check_supported_type(raw_name: str) -> None:
|
| 54 |
+
ext = os.path.splitext(raw_name)[1].lower()
|
| 55 |
+
if ext != ".pdf" and ext not in IMAGE_MIME_TYPES and ext not in PLAIN_TEXT_EXTS:
|
| 56 |
+
raise HTTPException(
|
| 57 |
+
status_code=415,
|
| 58 |
+
detail="This file type isn't supported. Upload a PDF, an image, or a text file "
|
| 59 |
+
"(.txt, .md, .csv, .json, .log).",
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def read_upload(file: UploadFile) -> bytes:
|
| 64 |
+
"""Read the upload, refusing files over MAX_UPLOAD_MB without reading the whole thing."""
|
| 65 |
+
data = file.file.read(MAX_UPLOAD_BYTES + 1)
|
| 66 |
+
if len(data) > MAX_UPLOAD_BYTES:
|
| 67 |
+
raise HTTPException(
|
| 68 |
+
status_code=413,
|
| 69 |
+
detail=f"File is too large. The limit is {MAX_UPLOAD_MB:g} MB.",
|
| 70 |
+
)
|
| 71 |
+
return data
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@dataclass
|
| 75 |
+
class Extracted:
|
| 76 |
+
text: str
|
| 77 |
+
note: str
|
| 78 |
+
page_starts: PageStarts | None = None # where each PDF page starts in `text`
|
| 79 |
+
pages_sent_to_ai: int = 0 # pages Sarvam Vision was asked to read (for cost tracking)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _read_pdf(data: bytes) -> Extracted:
|
| 83 |
+
local_error: Exception | None = None
|
| 84 |
+
try:
|
| 85 |
+
local_pages = pdf_page_texts(data)
|
| 86 |
+
except Exception as e: # not a readable PDF for PyMuPDF; Sarvam may still manage
|
| 87 |
+
local_pages, local_error = [], e
|
| 88 |
+
text, note, ai_pages = llm_pipeline.transcribe_pdf_with_pages(data)
|
| 89 |
+
sent = (len(local_pages) or 1) if llm_pipeline._sarvam_api_key() else 0
|
| 90 |
+
if (text or "").strip():
|
| 91 |
+
# Find each page inside Sarvam's text: its own per-page text first, else PyMuPDF's.
|
| 92 |
+
starts = anchor_page_starts(text, ai_pages) or anchor_page_starts(text, local_pages)
|
| 93 |
+
return Extracted(text, note or "", starts, sent)
|
| 94 |
+
if local_error is not None:
|
| 95 |
+
raise local_error
|
| 96 |
+
joined, starts = join_pages(local_pages)
|
| 97 |
+
return Extracted(joined, note or "used_pdf_parser_fallback", starts if len(starts) > 1 else None, sent)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def extract_text(raw_name: str, data: bytes) -> Extracted:
|
| 101 |
+
"""
|
| 102 |
+
Read the text of a PDF, image or plain-text file of a supported type.
|
| 103 |
+
Raises ExtractionError when no text can be read.
|
| 104 |
+
"""
|
| 105 |
+
ext = os.path.splitext(raw_name)[1].lower()
|
| 106 |
+
try:
|
| 107 |
+
if ext == ".pdf":
|
| 108 |
+
result = _read_pdf(data)
|
| 109 |
+
elif ext in IMAGE_MIME_TYPES:
|
| 110 |
+
text, note = llm_pipeline.transcribe_handwritten_image(data, IMAGE_MIME_TYPES[ext])
|
| 111 |
+
sent = 1 if llm_pipeline._sarvam_api_key() else 0
|
| 112 |
+
if not (text or "").strip():
|
| 113 |
+
text = extract_text_from_image_bytes(data)
|
| 114 |
+
note = note or "used_tesseract_fallback"
|
| 115 |
+
result = Extracted(text, note or "", None, sent)
|
| 116 |
+
else:
|
| 117 |
+
result = Extracted(data.decode("utf-8", errors="replace"), "plain_text")
|
| 118 |
+
except Exception as e:
|
| 119 |
+
logger.exception("Text extraction failed for %s", raw_name)
|
| 120 |
+
raise ExtractionError("Couldn't read this file. It may be damaged or password-protected.") from e
|
| 121 |
+
stripped = (result.text or "").strip()
|
| 122 |
+
if not stripped:
|
| 123 |
+
raise ExtractionError("Couldn't find any text in this file.")
|
| 124 |
+
if stripped != result.text and result.page_starts:
|
| 125 |
+
shift = len(result.text) - len(result.text.lstrip())
|
| 126 |
+
result.page_starts = [(max(0, off - shift), page) for off, page in result.page_starts]
|
| 127 |
+
result.text = stripped
|
| 128 |
+
return result
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def extract_text_or_http_error(raw_name: str, data: bytes) -> Extracted:
|
| 132 |
+
try:
|
| 133 |
+
return extract_text(raw_name, data)
|
| 134 |
+
except ExtractionError as e:
|
| 135 |
+
raise HTTPException(status_code=422, detail=str(e))
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def save_note_text(user_id: str, folder: str, raw_name: str, text: str, page_starts: PageStarts | None = None) -> dict:
|
| 139 |
+
"""Save text for search and as the file's stored text, then add the file to the tree."""
|
| 140 |
+
rel_path = f"{folder}/{raw_name}" if folder else raw_name
|
| 141 |
+
ingest_result = ingest_text_for_path(user_id, rel_path, raw_name, text, page_starts)
|
| 142 |
+
try:
|
| 143 |
+
user_document_upsert(user_id, rel_path, text, raw_name)
|
| 144 |
+
except Exception:
|
| 145 |
+
# Search chunks are the primary copy; the full-text copy is used for viewing/editing.
|
| 146 |
+
logger.warning("Stored-text write failed for %s", rel_path, exc_info=True)
|
| 147 |
+
with user_lock(user_id):
|
| 148 |
+
tree = get_vfs_tree_clean(user_id)
|
| 149 |
+
vfs_set_tree(user_id, tree_add_file(tree, folder, raw_name))
|
| 150 |
+
return ingest_result
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# ---------- Background upload jobs ----------
|
| 154 |
+
_executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="upload")
|
| 155 |
+
_jobs: dict[str, dict] = {}
|
| 156 |
+
_jobs_lock = threading.Lock()
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _public(job: dict) -> dict:
|
| 160 |
+
return {k: job[k] for k in ("job_id", "status", "path", "name", "error", "message")}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _prune_locked(now: float) -> None:
|
| 164 |
+
old = [
|
| 165 |
+
jid
|
| 166 |
+
for jid, j in _jobs.items()
|
| 167 |
+
if j["status"] in ("done", "failed") and now - j["updated_at"] > JOB_KEEP_SECONDS
|
| 168 |
+
]
|
| 169 |
+
for jid in old:
|
| 170 |
+
del _jobs[jid]
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _set(job_id: str, **fields) -> None:
|
| 174 |
+
with _jobs_lock:
|
| 175 |
+
job = _jobs.get(job_id)
|
| 176 |
+
if job:
|
| 177 |
+
job.update(fields, updated_at=time.time())
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _process(job_id: str, user_id: str, folder: str, raw_name: str, data: bytes) -> None:
|
| 181 |
+
_set(job_id, status="processing")
|
| 182 |
+
try:
|
| 183 |
+
extracted = extract_text(raw_name, data)
|
| 184 |
+
usage.record(user_id, pages_read=extracted.pages_sent_to_ai)
|
| 185 |
+
result = save_note_text(user_id, folder, raw_name, extracted.text, extracted.page_starts)
|
| 186 |
+
_set(job_id, status="done", message=f"Ready: {result.get('chunks_created', 0)} searchable sections.")
|
| 187 |
+
except ExtractionError as e:
|
| 188 |
+
usage.record(user_id, upload_failures=1)
|
| 189 |
+
_set(job_id, status="failed", error=str(e))
|
| 190 |
+
except Exception as e:
|
| 191 |
+
logger.exception("Upload job %s failed", job_id)
|
| 192 |
+
usage.record(user_id, upload_failures=1)
|
| 193 |
+
alerts.notify("upload-crash", f"Upload job failed unexpectedly: {type(e).__name__}: {e}")
|
| 194 |
+
_set(job_id, status="failed", error=f"Couldn't save '{raw_name}' for search. Please try again.")
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def submit_upload_job(user_id: str, folder: str, raw_name: str, data: bytes) -> dict:
|
| 198 |
+
now = time.time()
|
| 199 |
+
with _jobs_lock:
|
| 200 |
+
_prune_locked(now)
|
| 201 |
+
active = sum(1 for j in _jobs.values() if j["user_id"] == user_id and j["status"] in ("queued", "processing"))
|
| 202 |
+
if active >= MAX_ACTIVE_UPLOADS_PER_USER:
|
| 203 |
+
raise HTTPException(
|
| 204 |
+
status_code=429,
|
| 205 |
+
detail=f"You already have {active} files being processed. Please wait for them to finish.",
|
| 206 |
+
)
|
| 207 |
+
job_id = uuid.uuid4().hex
|
| 208 |
+
job = {
|
| 209 |
+
"job_id": job_id,
|
| 210 |
+
"user_id": user_id,
|
| 211 |
+
"status": "queued",
|
| 212 |
+
"path": f"{folder}/{raw_name}" if folder else raw_name,
|
| 213 |
+
"name": raw_name,
|
| 214 |
+
"error": None,
|
| 215 |
+
"message": None,
|
| 216 |
+
"created_at": now,
|
| 217 |
+
"updated_at": now,
|
| 218 |
+
}
|
| 219 |
+
_jobs[job_id] = job
|
| 220 |
+
# Snapshot before the worker starts: a fast failure must not change the reply mid-build.
|
| 221 |
+
reply = _public(job)
|
| 222 |
+
_executor.submit(_process, job_id, user_id, folder, raw_name, data)
|
| 223 |
+
return reply
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def get_job(user_id: str, job_id: str) -> dict | None:
|
| 227 |
+
with _jobs_lock:
|
| 228 |
+
job = _jobs.get(job_id)
|
| 229 |
+
return _public(job) if job and job["user_id"] == user_id else None
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def list_jobs(user_id: str) -> list[dict]:
|
| 233 |
+
with _jobs_lock:
|
| 234 |
+
_prune_locked(time.time())
|
| 235 |
+
mine = [j for j in _jobs.values() if j["user_id"] == user_id]
|
| 236 |
+
mine.sort(key=lambda j: j["created_at"], reverse=True)
|
| 237 |
+
return [_public(j) for j in mine]
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def forget_user_jobs(user_id: str) -> None:
|
| 241 |
+
with _jobs_lock:
|
| 242 |
+
for jid in [jid for jid, j in _jobs.items() if j["user_id"] == user_id]:
|
| 243 |
+
del _jobs[jid]
|
backend/usage.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Counting what each student does per day: questions, uploads, pages read by Sarvam Vision, AI tokens,
|
| 3 |
+
flashcard reviews, ratings. Used for the admin page, cost estimates, streaks, and the monthly budget.
|
| 4 |
+
|
| 5 |
+
One small record per user per day in the `usage_daily` collection.
|
| 6 |
+
"""
|
| 7 |
+
import datetime as dt
|
| 8 |
+
import logging
|
| 9 |
+
import threading
|
| 10 |
+
import time
|
| 11 |
+
from zoneinfo import ZoneInfo
|
| 12 |
+
|
| 13 |
+
from fastapi import HTTPException
|
| 14 |
+
|
| 15 |
+
from backend import settings
|
| 16 |
+
from backend.chroma_store import _dummy_embedding, _get_or_create_collection, get_all, short_id
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
COUNTERS = (
|
| 21 |
+
"questions",
|
| 22 |
+
"uploads",
|
| 23 |
+
"pages_read",
|
| 24 |
+
"upload_failures",
|
| 25 |
+
"study_requests",
|
| 26 |
+
"reviews",
|
| 27 |
+
"prompt_tokens",
|
| 28 |
+
"completion_tokens",
|
| 29 |
+
"ratings_up",
|
| 30 |
+
"ratings_down",
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
_lock = threading.Lock()
|
| 34 |
+
_month_cost: dict[str, float] = {} # "YYYY-MM" -> estimated cost so far (filled lazily from the database)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def tz() -> ZoneInfo:
|
| 38 |
+
try:
|
| 39 |
+
return ZoneInfo(settings.APP_TIMEZONE)
|
| 40 |
+
except Exception:
|
| 41 |
+
return ZoneInfo("UTC")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def today(now: float | None = None) -> dt.date:
|
| 45 |
+
return dt.datetime.fromtimestamp(now if now is not None else time.time(), tz()).date()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def day_num(day: dt.date) -> int:
|
| 49 |
+
return day.year * 10000 + day.month * 100 + day.day
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _collection():
|
| 53 |
+
return _get_or_create_collection("usage_daily")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def prices_set() -> bool:
|
| 57 |
+
return any(
|
| 58 |
+
(settings.AI_PRICE_PER_PAGE, settings.AI_PRICE_PER_1K_INPUT_TOKENS, settings.AI_PRICE_PER_1K_OUTPUT_TOKENS)
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def cost_of(counts: dict) -> float:
|
| 63 |
+
return (
|
| 64 |
+
float(counts.get("pages_read") or 0) * settings.AI_PRICE_PER_PAGE
|
| 65 |
+
+ float(counts.get("prompt_tokens") or 0) / 1000 * settings.AI_PRICE_PER_1K_INPUT_TOKENS
|
| 66 |
+
+ float(counts.get("completion_tokens") or 0) / 1000 * settings.AI_PRICE_PER_1K_OUTPUT_TOKENS
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def record(user_id: str, **increments: int) -> None:
|
| 71 |
+
"""Add to today's counters for a user. Never raises: counting must not break the request."""
|
| 72 |
+
increments = {k: int(v) for k, v in increments.items() if k in COUNTERS and v}
|
| 73 |
+
if not user_id or not increments:
|
| 74 |
+
return
|
| 75 |
+
day = today()
|
| 76 |
+
month = f"{day.year:04d}-{day.month:02d}"
|
| 77 |
+
rid = short_id("u", user_id, day.isoformat())
|
| 78 |
+
try:
|
| 79 |
+
with _lock:
|
| 80 |
+
col = _collection()
|
| 81 |
+
res = col.get(ids=[rid], include=["metadatas"])
|
| 82 |
+
meta = dict((res.get("metadatas") or [{}])[0] or {}) if res.get("ids") else {
|
| 83 |
+
"user_id": user_id,
|
| 84 |
+
"day": day.isoformat(),
|
| 85 |
+
"day_num": day_num(day),
|
| 86 |
+
"month": month,
|
| 87 |
+
}
|
| 88 |
+
for k, v in increments.items():
|
| 89 |
+
meta[k] = int(meta.get(k) or 0) + v
|
| 90 |
+
col.upsert(ids=[rid], documents=[""], embeddings=[_dummy_embedding()], metadatas=[meta])
|
| 91 |
+
if month in _month_cost:
|
| 92 |
+
_month_cost[month] += cost_of(increments)
|
| 93 |
+
except Exception:
|
| 94 |
+
logger.warning("Usage counting failed for %s", user_id, exc_info=True)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def records_since(start: dt.date, user_id: str | None = None) -> list[dict]:
|
| 98 |
+
where: dict = {"day_num": {"$gte": day_num(start)}}
|
| 99 |
+
if user_id:
|
| 100 |
+
where = {"$and": [where, {"user_id": user_id}]}
|
| 101 |
+
res = get_all(_collection(), where=where, include=["metadatas"])
|
| 102 |
+
return [m or {} for m in res.get("metadatas") or []]
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def month_cost(now: float | None = None) -> float:
|
| 106 |
+
day = today(now)
|
| 107 |
+
month = f"{day.year:04d}-{day.month:02d}"
|
| 108 |
+
with _lock:
|
| 109 |
+
if month not in _month_cost:
|
| 110 |
+
res = get_all(_collection(), where={"month": month}, include=["metadatas"])
|
| 111 |
+
_month_cost[month] = sum(cost_of(m or {}) for m in res.get("metadatas") or [])
|
| 112 |
+
return _month_cost[month]
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def check_budget() -> None:
|
| 116 |
+
"""Pause paid AI work (HTTP 503) once this month's estimated cost reaches AI_MONTHLY_BUDGET."""
|
| 117 |
+
if settings.AI_MONTHLY_BUDGET <= 0 or not prices_set():
|
| 118 |
+
return
|
| 119 |
+
try:
|
| 120 |
+
spent = month_cost()
|
| 121 |
+
except Exception:
|
| 122 |
+
logger.warning("Budget check failed; allowing the request", exc_info=True)
|
| 123 |
+
return
|
| 124 |
+
if spent >= settings.AI_MONTHLY_BUDGET:
|
| 125 |
+
raise HTTPException(
|
| 126 |
+
status_code=503,
|
| 127 |
+
detail="NoteScanner has used this month's AI budget, so reading files, answers and study "
|
| 128 |
+
"tools are paused until next month. Your notes and flashcard reviews still work.",
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def reset_cache() -> None:
|
| 133 |
+
with _lock:
|
| 134 |
+
_month_cost.clear()
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def delete_user(user_id: str) -> None:
|
| 138 |
+
from backend.chroma_store import delete_ids
|
| 139 |
+
|
| 140 |
+
col = _collection()
|
| 141 |
+
delete_ids(col, get_all(col, where={"user_id": user_id}, include=[])["ids"])
|
backend/vfs_tree.py
CHANGED
|
@@ -144,6 +144,7 @@ def tree_move_path(tree: list, from_path: str, to_folder: str, new_name: str | N
|
|
| 144 |
return n
|
| 145 |
|
| 146 |
rebased = rebase(removed)
|
|
|
|
| 147 |
children = ensure_folder_chain(t, dest_parent)
|
| 148 |
children.append(rebased)
|
| 149 |
return t
|
|
|
|
| 144 |
return n
|
| 145 |
|
| 146 |
rebased = rebase(removed)
|
| 147 |
+
rebased["name"] = nm
|
| 148 |
children = ensure_folder_chain(t, dest_parent)
|
| 149 |
children.append(rebased)
|
| 150 |
return t
|
docker-compose.yml
DELETED
|
@@ -1,43 +0,0 @@
|
|
| 1 |
-
version: "3.9"
|
| 2 |
-
services:
|
| 3 |
-
# Omit or stop this service if you use Chroma Cloud (CHROMA_API_KEY in .env).
|
| 4 |
-
chromadb:
|
| 5 |
-
image: chromadb/chroma
|
| 6 |
-
container_name: notescanner-chromadb
|
| 7 |
-
ports:
|
| 8 |
-
- "8100:8000"
|
| 9 |
-
volumes:
|
| 10 |
-
- chroma_data:/chroma/chroma
|
| 11 |
-
|
| 12 |
-
backend:
|
| 13 |
-
build: .
|
| 14 |
-
container_name: notescanner-backend
|
| 15 |
-
depends_on:
|
| 16 |
-
- chromadb
|
| 17 |
-
env_file:
|
| 18 |
-
- .env
|
| 19 |
-
environment:
|
| 20 |
-
- CHROMA_HOST=chromadb
|
| 21 |
-
- CHROMA_PORT=8000
|
| 22 |
-
ports:
|
| 23 |
-
- "8000:8000"
|
| 24 |
-
command: ["uvicorn", "backend.api:app", "--host", "0.0.0.0", "--port", "8000"]
|
| 25 |
-
|
| 26 |
-
frontend:
|
| 27 |
-
build:
|
| 28 |
-
context: ./frontend/my-app
|
| 29 |
-
dockerfile: Dockerfile
|
| 30 |
-
container_name: notescanner-frontend
|
| 31 |
-
depends_on:
|
| 32 |
-
- backend
|
| 33 |
-
ports:
|
| 34 |
-
- "5173:5173"
|
| 35 |
-
volumes:
|
| 36 |
-
- ./frontend/my-app/src:/app/src
|
| 37 |
-
- ./frontend/my-app/public:/app/public
|
| 38 |
-
- ./frontend/my-app/index.html:/app/index.html
|
| 39 |
-
- ./frontend/my-app/vite.config.js:/app/vite.config.js
|
| 40 |
-
command: ["npm", "run", "dev", "--", "--host"]
|
| 41 |
-
|
| 42 |
-
volumes:
|
| 43 |
-
chroma_data:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/my-app/.dockerignore
DELETED
|
@@ -1,11 +0,0 @@
|
|
| 1 |
-
node_modules
|
| 2 |
-
npm-debug.log
|
| 3 |
-
.git
|
| 4 |
-
.gitignore
|
| 5 |
-
README.md
|
| 6 |
-
.env
|
| 7 |
-
.nyc_output
|
| 8 |
-
coverage
|
| 9 |
-
.DS_Store
|
| 10 |
-
*.log
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/my-app/.gitignore
DELETED
|
@@ -1,24 +0,0 @@
|
|
| 1 |
-
# Logs
|
| 2 |
-
logs
|
| 3 |
-
*.log
|
| 4 |
-
npm-debug.log*
|
| 5 |
-
yarn-debug.log*
|
| 6 |
-
yarn-error.log*
|
| 7 |
-
pnpm-debug.log*
|
| 8 |
-
lerna-debug.log*
|
| 9 |
-
|
| 10 |
-
node_modules
|
| 11 |
-
dist
|
| 12 |
-
dist-ssr
|
| 13 |
-
*.local
|
| 14 |
-
|
| 15 |
-
# Editor directories and files
|
| 16 |
-
.vscode/*
|
| 17 |
-
!.vscode/extensions.json
|
| 18 |
-
.idea
|
| 19 |
-
.DS_Store
|
| 20 |
-
*.suo
|
| 21 |
-
*.ntvs*
|
| 22 |
-
*.njsproj
|
| 23 |
-
*.sln
|
| 24 |
-
*.sw?
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/my-app/Dockerfile
DELETED
|
@@ -1,22 +0,0 @@
|
|
| 1 |
-
FROM arm64v8/node:20-bookworm-slim
|
| 2 |
-
|
| 3 |
-
RUN npm install -g npm@latest
|
| 4 |
-
|
| 5 |
-
WORKDIR /app
|
| 6 |
-
|
| 7 |
-
COPY package*.json ./
|
| 8 |
-
|
| 9 |
-
RUN rm -rf node_modules package-lock.json && \
|
| 10 |
-
npm cache clean --force && \
|
| 11 |
-
npm install --legacy-peer-deps --platform=linux --arch=arm64 --no-audit --no-fund
|
| 12 |
-
|
| 13 |
-
RUN npm install --platform=linux --arch=arm64 @rollup/rollup-linux-arm64-gnu --no-audit --no-fund
|
| 14 |
-
|
| 15 |
-
COPY . .
|
| 16 |
-
|
| 17 |
-
RUN chown -R node:node /app
|
| 18 |
-
USER node
|
| 19 |
-
|
| 20 |
-
EXPOSE 5173
|
| 21 |
-
|
| 22 |
-
CMD ["npm", "run", "dev", "--", "--host"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/my-app/eslint.config.js
DELETED
|
@@ -1,29 +0,0 @@
|
|
| 1 |
-
import js from '@eslint/js'
|
| 2 |
-
import globals from 'globals'
|
| 3 |
-
import reactHooks from 'eslint-plugin-react-hooks'
|
| 4 |
-
import reactRefresh from 'eslint-plugin-react-refresh'
|
| 5 |
-
import { defineConfig, globalIgnores } from 'eslint/config'
|
| 6 |
-
|
| 7 |
-
export default defineConfig([
|
| 8 |
-
globalIgnores(['dist']),
|
| 9 |
-
{
|
| 10 |
-
files: ['**/*.{js,jsx}'],
|
| 11 |
-
extends: [
|
| 12 |
-
js.configs.recommended,
|
| 13 |
-
reactHooks.configs['recommended-latest'],
|
| 14 |
-
reactRefresh.configs.vite,
|
| 15 |
-
],
|
| 16 |
-
languageOptions: {
|
| 17 |
-
ecmaVersion: 2020,
|
| 18 |
-
globals: globals.browser,
|
| 19 |
-
parserOptions: {
|
| 20 |
-
ecmaVersion: 'latest',
|
| 21 |
-
ecmaFeatures: { jsx: true },
|
| 22 |
-
sourceType: 'module',
|
| 23 |
-
},
|
| 24 |
-
},
|
| 25 |
-
rules: {
|
| 26 |
-
'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
|
| 27 |
-
},
|
| 28 |
-
},
|
| 29 |
-
])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/my-app/index.html
DELETED
|
@@ -1,12 +0,0 @@
|
|
| 1 |
-
<!doctype html>
|
| 2 |
-
<html lang="en">
|
| 3 |
-
<head>
|
| 4 |
-
<meta charset="UTF-8" />
|
| 5 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
| 6 |
-
<title>NoteScanner</title>
|
| 7 |
-
</head>
|
| 8 |
-
<body>
|
| 9 |
-
<div id="root"></div>
|
| 10 |
-
<script type="module" src="/src/main.jsx"></script>
|
| 11 |
-
</body>
|
| 12 |
-
</html>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/my-app/package.json
DELETED
|
@@ -1,29 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"name": "my-app",
|
| 3 |
-
"private": true,
|
| 4 |
-
"version": "0.0.0",
|
| 5 |
-
"type": "module",
|
| 6 |
-
"scripts": {
|
| 7 |
-
"dev": "vite",
|
| 8 |
-
"build": "vite build",
|
| 9 |
-
"lint": "eslint .",
|
| 10 |
-
"preview": "vite preview"
|
| 11 |
-
},
|
| 12 |
-
"dependencies": {
|
| 13 |
-
"@xyflow/react": "^12.10.2",
|
| 14 |
-
"react": "^19.1.1",
|
| 15 |
-
"react-dom": "^19.1.1",
|
| 16 |
-
"react-icons": "^5.5.0"
|
| 17 |
-
},
|
| 18 |
-
"devDependencies": {
|
| 19 |
-
"@eslint/js": "^9.35.0",
|
| 20 |
-
"@types/react": "^19.1.13",
|
| 21 |
-
"@types/react-dom": "^19.1.9",
|
| 22 |
-
"@vitejs/plugin-react": "^5.0.2",
|
| 23 |
-
"eslint": "^9.35.0",
|
| 24 |
-
"eslint-plugin-react-hooks": "^5.2.0",
|
| 25 |
-
"eslint-plugin-react-refresh": "^0.4.20",
|
| 26 |
-
"globals": "^16.4.0",
|
| 27 |
-
"vite": "^7.1.6"
|
| 28 |
-
}
|
| 29 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/my-app/src/App.jsx
DELETED
|
@@ -1,67 +0,0 @@
|
|
| 1 |
-
import { useState, useCallback, useEffect } from "react";
|
| 2 |
-
import { getSessionId, removeSession, ensureGuestId, isSignedIn } from "./auth";
|
| 3 |
-
import Login from "./pages/Login";
|
| 4 |
-
import Register from "./pages/Register";
|
| 5 |
-
import Home from "./pages/Home";
|
| 6 |
-
import ChatPage from "./pages/ChatPage";
|
| 7 |
-
|
| 8 |
-
function App() {
|
| 9 |
-
const [signedIn, setSignedIn] = useState(isSignedIn());
|
| 10 |
-
const [authView, setAuthView] = useState(null);
|
| 11 |
-
|
| 12 |
-
useEffect(() => {
|
| 13 |
-
if (!getSessionId()) ensureGuestId();
|
| 14 |
-
}, []);
|
| 15 |
-
|
| 16 |
-
const onLogin = useCallback(() => {
|
| 17 |
-
setSignedIn(true);
|
| 18 |
-
setAuthView(null);
|
| 19 |
-
}, []);
|
| 20 |
-
|
| 21 |
-
const onLogout = useCallback(() => {
|
| 22 |
-
removeSession();
|
| 23 |
-
setSignedIn(false);
|
| 24 |
-
ensureGuestId();
|
| 25 |
-
}, []);
|
| 26 |
-
|
| 27 |
-
const openSignIn = useCallback(() => setAuthView("login"), []);
|
| 28 |
-
const openSignUp = useCallback(() => setAuthView("register"), []);
|
| 29 |
-
|
| 30 |
-
return (
|
| 31 |
-
<>
|
| 32 |
-
{signedIn ? (
|
| 33 |
-
<Home
|
| 34 |
-
onLogout={onLogout}
|
| 35 |
-
onSignInClick={openSignIn}
|
| 36 |
-
signedIn={signedIn}
|
| 37 |
-
/>
|
| 38 |
-
) : (
|
| 39 |
-
<ChatPage onSignInClick={openSignIn} />
|
| 40 |
-
)}
|
| 41 |
-
{authView === "login" && (
|
| 42 |
-
<div className="auth-overlay" onClick={() => setAuthView(null)}>
|
| 43 |
-
<div className="auth-overlay-content" onClick={(e) => e.stopPropagation()}>
|
| 44 |
-
<Login
|
| 45 |
-
onLogin={onLogin}
|
| 46 |
-
onSwitchToRegister={() => setAuthView("register")}
|
| 47 |
-
onClose={() => setAuthView(null)}
|
| 48 |
-
/>
|
| 49 |
-
</div>
|
| 50 |
-
</div>
|
| 51 |
-
)}
|
| 52 |
-
{authView === "register" && (
|
| 53 |
-
<div className="auth-overlay" onClick={() => setAuthView(null)}>
|
| 54 |
-
<div className="auth-overlay-content" onClick={(e) => e.stopPropagation()}>
|
| 55 |
-
<Register
|
| 56 |
-
onRegister={onLogin}
|
| 57 |
-
onSwitchToLogin={() => setAuthView("login")}
|
| 58 |
-
onClose={() => setAuthView(null)}
|
| 59 |
-
/>
|
| 60 |
-
</div>
|
| 61 |
-
</div>
|
| 62 |
-
)}
|
| 63 |
-
</>
|
| 64 |
-
);
|
| 65 |
-
}
|
| 66 |
-
|
| 67 |
-
export default App;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/my-app/src/auth.js
DELETED
|
@@ -1,100 +0,0 @@
|
|
| 1 |
-
import { API_BASE } from "./config";
|
| 2 |
-
import { getBlobUrlForPath } from "./localFileStore";
|
| 3 |
-
|
| 4 |
-
const SESSION_KEY = "notescanner_session_id";
|
| 5 |
-
const GUEST_KEY = "notescanner_guest_id";
|
| 6 |
-
const USER_NAME_KEY = "notescanner_user_name";
|
| 7 |
-
const SESSION_HEADER = "X-Session-Id";
|
| 8 |
-
const GUEST_HEADER = "X-Guest-Id";
|
| 9 |
-
|
| 10 |
-
export function getSessionId() {
|
| 11 |
-
return localStorage.getItem(SESSION_KEY);
|
| 12 |
-
}
|
| 13 |
-
|
| 14 |
-
export function setSessionId(sessionId, userName = null) {
|
| 15 |
-
localStorage.setItem(SESSION_KEY, sessionId);
|
| 16 |
-
localStorage.removeItem(GUEST_KEY);
|
| 17 |
-
if (userName != null) localStorage.setItem(USER_NAME_KEY, userName);
|
| 18 |
-
}
|
| 19 |
-
|
| 20 |
-
export function removeSession() {
|
| 21 |
-
localStorage.removeItem(SESSION_KEY);
|
| 22 |
-
localStorage.removeItem(USER_NAME_KEY);
|
| 23 |
-
}
|
| 24 |
-
|
| 25 |
-
export function getUserName() {
|
| 26 |
-
return localStorage.getItem(USER_NAME_KEY) || "";
|
| 27 |
-
}
|
| 28 |
-
|
| 29 |
-
export function setUserName(name) {
|
| 30 |
-
if (name != null) localStorage.setItem(USER_NAME_KEY, name);
|
| 31 |
-
}
|
| 32 |
-
|
| 33 |
-
export function getGuestId() {
|
| 34 |
-
return localStorage.getItem(GUEST_KEY);
|
| 35 |
-
}
|
| 36 |
-
|
| 37 |
-
export function setGuestId(guestId) {
|
| 38 |
-
localStorage.setItem(GUEST_KEY, guestId);
|
| 39 |
-
}
|
| 40 |
-
|
| 41 |
-
const _apiBase = () => API_BASE || "http://localhost:8000";
|
| 42 |
-
|
| 43 |
-
/** Ensure we have a guest id (fetch from backend if missing). Returns a promise that resolves when ready. */
|
| 44 |
-
export async function ensureGuestId() {
|
| 45 |
-
if (getSessionId()) return;
|
| 46 |
-
let g = getGuestId();
|
| 47 |
-
if (!g) {
|
| 48 |
-
const res = await fetch(`${_apiBase()}/guest_id`);
|
| 49 |
-
let data = {};
|
| 50 |
-
try {
|
| 51 |
-
data = await res.json();
|
| 52 |
-
} catch (_) {}
|
| 53 |
-
if (data.guest_id) {
|
| 54 |
-
setGuestId(data.guest_id);
|
| 55 |
-
g = data.guest_id;
|
| 56 |
-
}
|
| 57 |
-
}
|
| 58 |
-
return g;
|
| 59 |
-
}
|
| 60 |
-
|
| 61 |
-
export function getAuthHeadersForFetch() {
|
| 62 |
-
const sessionId = getSessionId();
|
| 63 |
-
if (sessionId) return { [SESSION_HEADER]: sessionId };
|
| 64 |
-
const guestId = getGuestId();
|
| 65 |
-
if (guestId) return { [GUEST_HEADER]: guestId };
|
| 66 |
-
return {};
|
| 67 |
-
}
|
| 68 |
-
|
| 69 |
-
/** Blob URL for a path if this device has a local copy (e.g. after upload). Server does not store binaries. */
|
| 70 |
-
export function getFileUrl(path) {
|
| 71 |
-
return getBlobUrlForPath(path) || "";
|
| 72 |
-
}
|
| 73 |
-
|
| 74 |
-
export function authFetch(url, options = {}) {
|
| 75 |
-
const headers = { ...getAuthHeadersForFetch(), ...options.headers };
|
| 76 |
-
return fetch(url, { ...options, headers });
|
| 77 |
-
}
|
| 78 |
-
|
| 79 |
-
/** Readable string from FastAPI/JSON error bodies (detail, error, message). */
|
| 80 |
-
export function apiErrorMessage(data, res) {
|
| 81 |
-
const status = res?.status;
|
| 82 |
-
if (!data || typeof data !== "object") {
|
| 83 |
-
return status ? `Request failed (HTTP ${status})` : "Request failed";
|
| 84 |
-
}
|
| 85 |
-
if (typeof data.detail === "string" && data.detail) return data.detail;
|
| 86 |
-
if (Array.isArray(data.detail) && data.detail.length) {
|
| 87 |
-
const parts = data.detail.map((x) =>
|
| 88 |
-
x && typeof x === "object" && x.msg != null ? String(x.msg) : String(x),
|
| 89 |
-
);
|
| 90 |
-
const joined = parts.join("; ").trim();
|
| 91 |
-
if (joined) return joined;
|
| 92 |
-
}
|
| 93 |
-
if (data.error) return String(data.error);
|
| 94 |
-
if (data.message) return String(data.message);
|
| 95 |
-
return status ? `Request failed (HTTP ${status})` : "Request failed";
|
| 96 |
-
}
|
| 97 |
-
|
| 98 |
-
export function isSignedIn() {
|
| 99 |
-
return !!getSessionId();
|
| 100 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|