github-actions[bot] commited on
Commit
9c56a9c
·
1 Parent(s): e65f749

Deploy 041b90a from GitHub

Browse files
.dockerignore CHANGED
@@ -1,27 +1,13 @@
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
 
1
+ # Only backend/, requirements.txt and the Dockerfile are needed to build the server image.
 
 
 
 
 
 
2
  .env
3
  .env.*
4
  venv/
5
  .venv/
 
 
 
6
  tests/
7
+ scripts/
8
+ evals/
9
  **/__pycache__
10
  *.pyc
 
11
  .pytest_cache/
 
 
 
 
 
 
12
  *.log
13
  *.md
DEPLOYMENT.md DELETED
@@ -1,314 +0,0 @@
1
- # Free Deployment Checklist
2
-
3
- This project is set up for:
4
-
5
- - Frontend: GitHub Pages
6
- - Backend: Hugging Face Spaces (Docker)
7
-
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
-
55
- - `SARVAM_API_KEY`
56
-
57
- ### Recommended Space variables/secrets
58
-
59
- - `SARVAM_API_BASE` (optional, default works)
60
- - `SARVAM_MODEL_RAG` (optional)
61
- - `SARVAM_MODEL_STUDY` (optional)
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:
108
-
109
- - Chroma Cloud:
110
- - `CHROMA_API_KEY`
111
- - `CHROMA_TENANT`
112
- - `CHROMA_DATABASE`
113
- - OR self-hosted Chroma:
114
- - `CHROMA_HOST`
115
- - `CHROMA_PORT`
116
- - `CHROMA_SSL` (optional)
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
-
124
- 1. In your GitHub repo, go to **Settings -> Secrets and variables -> Actions -> New repository secret**.
125
- 2. Add this secret:
126
-
127
- - `VITE_API_URL` = `https://diptidhawade-NoteScanner.hf.space`
128
-
129
- 1. Push to `main` (or rerun workflow `Deploy to GitHub Pages`).
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:
147
- - `+` chat upload
148
- - query response
149
- - explorer upload
150
- - study generation
151
-
152
- ## 5) Shared course library and Interview.ai (Study AI + Ask AI)
153
-
154
- [Interview.ai](https://cherie-dips.github.io/SDE-Prep/) uses this backend in two ways:
155
-
156
- - **Study AI tab**: this frontend inside Interview.ai (`/NoteScanner/?embed=sde`), in Interview.ai's colours.
157
- Both sites are on `cherie-dips.github.io`, so they share the sign-in.
158
- - **Ask AI** in Interview.ai'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` | Interview.ai'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 Interview.ai, 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
@@ -22,11 +22,14 @@ RUN pip install --index-url https://download.pytorch.org/whl/cpu torch==2.8.0
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
 
@@ -37,5 +40,5 @@ EXPOSE 7860
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"]
 
22
  COPY requirements.txt .
23
  RUN pip install -r requirements.txt
24
 
25
+ # Download the search model and the re-checking model during the build (see backend/pipeline/models.py),
26
+ # so the server never downloads at run time and the first question after a restart is fast.
27
  RUN mkdir -p "$HF_HOME" \
28
+ && python -c "from sentence_transformers import CrossEncoder, SentenceTransformer; \
29
+ SentenceTransformer('intfloat/multilingual-e5-small'); CrossEncoder('cross-encoder/mmarco-mMiniLMv2-L12-H384-v1')" \
30
  && chown -R user:user "$HF_HOME"
31
+ ENV HF_HUB_OFFLINE=1 \
32
+ TOKENIZERS_PARALLELISM=false
33
 
34
  COPY --chown=user:user backend ./backend
35
 
 
40
  HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
41
  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
42
 
43
+ # One worker: upload jobs, the chat-upload cache, request limits and per-user locks live in process memory.
44
  CMD ["sh", "-c", "exec uvicorn backend.api:app --host 0.0.0.0 --port ${PORT:-7860} --workers 1"]
README.md CHANGED
@@ -1,461 +1,15 @@
1
  ---
2
- title: NoteScanner
3
  emoji: "📚"
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
- ![NoteScanner](frontend/my-app/public/app-page.png)
21
-
22
- **Also part of [Interview.ai](https://cherie-dips.github.io/SDE-Prep/).** There it is the **Study AI** tab
23
- (this app in Interview.ai's colours, with the same sign-in), and it powers **Ask AI** in Interview.ai'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 (Interview.ai)**
85
- - Course PDFs from Interview.ai'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 (Interview.ai 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-105b, with low reasoning effort):
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
- Interview.ai'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 Interview.ai can scroll to the exact spot.
216
- ```
217
-
218
- When Interview.ai 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, flashcards, quizzes and summaries (study tools use low reasoning effort). |
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 Interview.ai, 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-105b`), `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` (Interview.ai'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-interviewai-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.
 
1
  ---
2
+ title: Study AI server
3
  emoji: "📚"
4
+ colorFrom: green
5
+ colorTo: gray
6
  sdk: docker
7
  app_port: 7860
8
  pinned: false
9
  ---
10
 
11
+ # Study AI server
12
 
13
+ The server behind Interview.ai's Study AI tab and Ask AI panel: https://cherie-dips.github.io/SDE-Prep/
14
 
15
+ Code: https://github.com/cherie-dips/SDE-Prep/tree/main/server (deployed from there by GitHub Actions).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/alerts.py CHANGED
@@ -34,6 +34,6 @@ def notify(kind: str, message: str) -> bool:
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
 
34
  if now - _last_sent.get(kind, 0) < THROTTLE_SECONDS:
35
  return False
36
  _last_sent[kind] = now
37
+ text = f"Study AI alert ({kind}): {message[:1500]}"
38
  threading.Thread(target=_post, args=(text,), name="alert", daemon=True).start()
39
  return True
backend/api.py CHANGED
@@ -1,17 +1,19 @@
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
@@ -20,14 +22,23 @@ from backend.settings import MAX_CHAT_FILES_PER_SESSION, MAX_UPLOAD_MB, allowed_
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")
@@ -85,7 +96,7 @@ def health():
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,
 
1
+ """Study AI 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
+ import threading
9
  from contextlib import asynccontextmanager
10
 
11
  from fastapi import FastAPI, HTTPException, Request
12
  from fastapi.middleware.cors import CORSMiddleware
13
  from fastapi.responses import JSONResponse
14
 
15
+ from backend import alerts, db, library, neon_auth, onenote_sync, preferences, rate_limit, reminders, settings
16
+ from backend.pipeline import models
17
  from backend.auth import SESSION_HEADER
18
  from backend.routes import account, admin, chat, files, onenote, study
19
  from backend.routes import library as library_routes
 
22
  logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
23
  logger = logging.getLogger("notescanner")
24
 
25
+ def _warm_up_models() -> None:
26
+ try:
27
+ models.warm_up()
28
+ except Exception:
29
+ logger.exception("Loading the search models failed; they will load on the first question")
30
+
31
+
32
  @asynccontextmanager
33
  async def lifespan(_app: FastAPI):
34
+ db.init() # create the tables on first start (safe to repeat)
35
+ threading.Thread(target=_warm_up_models, name="warm-up", daemon=True).start()
36
  reminders.start() # daily review emails (only when SMTP is set up)
37
  library.start() # re-checks the shared course library (only when LIBRARY_SYNC_HOURS is set)
38
  yield
39
 
40
 
41
+ app = FastAPI(title="Study AI API", lifespan=lifespan)
42
 
43
 
44
  @app.middleware("http")
 
96
  def public_config():
97
  """Feature flags the frontend needs before sign-in."""
98
  return {
99
+ "password_reset_enabled": neon_auth.configured(),
100
  "onenote_configured": onenote_sync.is_configured(),
101
  "max_upload_mb": MAX_UPLOAD_MB,
102
  "max_chat_files": MAX_CHAT_FILES_PER_SESSION,
backend/auth.py CHANGED
@@ -1,48 +1,57 @@
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"
17
  GUEST_HEADER = "X-Guest-Id"
18
 
19
-
20
- def hash_password(password: str) -> str:
21
- return pwd_context.hash(password)
22
 
23
 
24
- def verify_password(plain: str, hashed: str) -> bool:
25
- return pwd_context.verify(plain, hashed)
26
-
27
-
28
- def create_session(user_id: str) -> str:
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:
 
1
+ """
2
+ Who is calling: a signed-in student (X-Session-Id, checked with Neon Auth) or a guest (X-Guest-Id).
3
+
4
+ The session id is the sign-in Neon Auth gave this server at sign-up or sign-in (backend/neon_auth.py).
5
+ A signed-in student also needs a row in the users table, made at sign-up with their privacy acceptance.
6
+ """
7
  import logging
8
  import uuid
9
 
10
  from fastapi import HTTPException, Request
11
 
12
+ from backend import neon_auth
13
+ from backend.store import user_sync
 
 
14
 
15
  logger = logging.getLogger(__name__)
16
 
 
 
17
  SESSION_HEADER = "X-Session-Id"
18
  GUEST_HEADER = "X-Guest-Id"
19
 
20
+ _synced: dict[str, neon_auth.User] = {} # last details copied to the users table, per user id
 
 
21
 
22
 
23
+ def signed_in_user(session_id: str) -> neon_auth.User | None:
24
+ """
25
+ The Neon Auth user for a live session that has a Study AI account, or None.
26
+ Raises HTTP 503 if the sign-in service or the database can't be reached.
27
+ """
28
+ try:
29
+ user = neon_auth.current_user(session_id)
30
+ except neon_auth.AuthError as e:
31
+ raise HTTPException(status_code=e.status if e.status >= 500 else 503, detail=e.message)
32
+ if not user:
33
+ return None
34
+ if _synced.get(user.id) == user:
35
+ return user
36
+ try:
37
+ known = user_sync(user.id, user.email, user.name, user.email_verified)
38
+ except Exception:
39
+ logger.exception("User lookup failed")
40
+ raise HTTPException(status_code=503, detail="Can't reach the database right now. Please try again in a moment.")
41
+ if not known:
42
+ return None # signed in to Neon, but never finished signing up here (or the account was deleted)
43
+ _synced[user.id] = user
44
+ return user
45
 
46
 
47
+ def forget_user(user_id: str) -> None:
48
+ _synced.pop(user_id, None)
49
+ neon_auth.forget_user(user_id)
50
 
51
 
52
+ def get_user_id_from_session(session_id: str | None) -> str | None:
53
+ user = signed_in_user((session_id or "").strip())
54
+ return user.id if user else None
 
 
 
 
 
 
 
55
 
56
 
57
  def _valid_guest_id(guest_id: str) -> bool:
backend/chroma_store.py DELETED
@@ -1,770 +0,0 @@
1
- """
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:
72
- api_key = (os.getenv("CHROMA_API_KEY") or "").strip()
73
- if api_key:
74
- tenant = (os.getenv("CHROMA_TENANT") or "").strip() or None
75
- database = (os.getenv("CHROMA_DATABASE") or "").strip() or None
76
- kwargs: dict = {"api_key": api_key}
77
- if tenant:
78
- kwargs["tenant"] = tenant
79
- if database:
80
- kwargs["database"] = database
81
- _global_client = chromadb.CloudClient(**kwargs)
82
- else:
83
- host = (os.getenv("CHROMA_HOST") or "localhost").strip()
84
- port_raw = (os.getenv("CHROMA_PORT") or "8100").strip()
85
- try:
86
- port = int(port_raw)
87
- except ValueError:
88
- port = 8100
89
- ssl = (os.getenv("CHROMA_SSL") or "").lower() in ("1", "true", "yes")
90
- _global_client = chromadb.HttpClient(host=host, port=port, ssl=ssl)
91
- return _global_client
92
-
93
-
94
- def _get_or_create_collection(name: str):
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 {}
227
- idx = i
228
- if isinstance(meta, dict) and meta.get("chunk_index") is not None:
229
- try:
230
- idx = int(meta["chunk_index"])
231
- except (TypeError, ValueError):
232
- idx = i
233
- text = (doc or "").strip()
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"
263
- return _get_or_create_collection(name)
264
-
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 ----------
381
- def get_users_collection():
382
- return _get_or_create_collection("users")
383
-
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 ----------
462
- def get_sessions_collection():
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]:
574
- raw = (text or "").encode("utf-8")
575
- if len(raw) <= max_bytes:
576
- return (text or ""), len(raw)
577
- cut = raw[: max(0, max_bytes)]
578
- while cut:
579
- try:
580
- return cut.decode("utf-8"), len(raw)
581
- except UnicodeDecodeError:
582
- cut = cut[:-1]
583
- return "", len(raw)
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):
672
- n += 1
673
- return n
674
-
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 ----------
688
- def get_onenote_tokens_collection():
689
- return _get_or_create_collection("onenote_tokens")
690
-
691
-
692
- def get_onenote_oauth_state_collection():
693
- return _get_or_create_collection("onenote_oauth_states")
694
-
695
-
696
- def _oauth_state_id(state: str) -> str:
697
- return f"state|{state}"
698
-
699
-
700
- def onenote_oauth_state_create(user_id: str, state: str, expires_at_epoch: int) -> None:
701
- col = get_onenote_oauth_state_collection()
702
- col.upsert(
703
- ids=[_oauth_state_id(state)],
704
- documents=[""],
705
- metadatas=[{"user_id": str(user_id), "expires_at": int(expires_at_epoch)}],
706
- embeddings=[_dummy_embedding()],
707
- )
708
-
709
-
710
- def onenote_oauth_state_pop_user_id(state: str) -> str | None:
711
- col = get_onenote_oauth_state_collection()
712
- sid = _oauth_state_id(state)
713
- try:
714
- res = col.get(ids=[sid], include=["metadatas"])
715
- if not res.get("ids"):
716
- return None
717
- meta = (res.get("metadatas") or [{}])[0] or {}
718
- try:
719
- exp = int(meta.get("expires_at") or 0)
720
- except Exception:
721
- exp = 0
722
- user_id = str(meta.get("user_id") or "")
723
- col.delete(ids=[sid])
724
- if not user_id:
725
- return None
726
- if exp and exp < int(time.time()):
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
-
734
- def onenote_token_upsert(user_id: str, token_payload: dict) -> None:
735
- col = get_onenote_tokens_collection()
736
- uid = str(user_id)
737
- try:
738
- raw = json.dumps(token_payload or {}, ensure_ascii=False)
739
- except Exception:
740
- raw = "{}"
741
- expires_at = 0
742
- try:
743
- expires_at = int((token_payload or {}).get("expires_at") or 0)
744
- except Exception:
745
- expires_at = 0
746
- col.upsert(
747
- ids=[uid],
748
- documents=[raw],
749
- metadatas=[{"user_id": uid, "expires_at": expires_at}],
750
- embeddings=[_dummy_embedding()],
751
- )
752
-
753
-
754
- def onenote_token_get(user_id: str) -> dict | None:
755
- col = get_onenote_tokens_collection()
756
- uid = str(user_id)
757
- try:
758
- res = col.get(ids=[uid], include=["documents"])
759
- if not res.get("ids"):
760
- return None
761
- raw = (res.get("documents") or ["{}"])[0] or "{}"
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/db.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The database: one Postgres (with the pgvector extension) for everything Study AI stores.
3
+
4
+ - Folders, file text, decks, usage and feedback are ordinary tables (SCHEMA). Accounts, passwords and
5
+ sign-ins belong to Neon Auth (its own neon_auth schema); `users` keeps Study AI's details per account.
6
+ - Note passages and their search fingerprints are two more tables, data_notes and data_library,
7
+ created and searched through LlamaIndex (see backend/pipeline/indexing.py).
8
+
9
+ DATABASE_URL points at it, e.g. postgresql://user:password@host/dbname?sslmode=require
10
+ (Neon and Supabase both offer a free Postgres with pgvector).
11
+ """
12
+ import logging
13
+ import threading
14
+ from contextlib import contextmanager
15
+
16
+ from sqlalchemy import create_engine, text
17
+ from sqlalchemy.engine import Connection, Engine
18
+
19
+ from backend import settings
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ # Keep in step with usage.COUNTERS (one column per daily counter).
24
+ SCHEMA = """
25
+ CREATE EXTENSION IF NOT EXISTS vector;
26
+
27
+ CREATE TABLE IF NOT EXISTS users (
28
+ id TEXT PRIMARY KEY, -- the Neon Auth user id
29
+ email TEXT NOT NULL UNIQUE,
30
+ name TEXT NOT NULL DEFAULT '',
31
+ email_verified BOOLEAN NOT NULL DEFAULT FALSE,
32
+ created_at BIGINT NOT NULL,
33
+ meta JSONB NOT NULL DEFAULT '{}'::jsonb -- preferences (pref_*), privacy acceptance, ...
34
+ );
35
+
36
+ CREATE TABLE IF NOT EXISTS folders (
37
+ user_id TEXT PRIMARY KEY,
38
+ tree JSONB NOT NULL DEFAULT '[]'::jsonb, -- the folder tree shown in the explorer
39
+ file_meta JSONB NOT NULL DEFAULT '{}'::jsonb -- per-file details, e.g. "main source"
40
+ );
41
+
42
+ CREATE TABLE IF NOT EXISTS documents (
43
+ user_id TEXT NOT NULL,
44
+ path TEXT NOT NULL,
45
+ original_filename TEXT NOT NULL DEFAULT '',
46
+ content TEXT NOT NULL DEFAULT '', -- the full text read from the file
47
+ truncated BOOLEAN NOT NULL DEFAULT FALSE,
48
+ updated_at BIGINT NOT NULL,
49
+ original_key TEXT NOT NULL DEFAULT '', -- the original PDF/photo in file storage ('' = none)
50
+ original_type TEXT NOT NULL DEFAULT '',
51
+ original_size BIGINT NOT NULL DEFAULT 0,
52
+ PRIMARY KEY (user_id, path)
53
+ );
54
+
55
+ CREATE TABLE IF NOT EXISTS decks (
56
+ id TEXT PRIMARY KEY,
57
+ user_id TEXT NOT NULL,
58
+ name TEXT NOT NULL,
59
+ source_path TEXT NOT NULL DEFAULT '',
60
+ created_at BIGINT NOT NULL
61
+ );
62
+ CREATE INDEX IF NOT EXISTS decks_user_id ON decks (user_id);
63
+
64
+ CREATE TABLE IF NOT EXISTS cards (
65
+ id TEXT PRIMARY KEY,
66
+ deck_id TEXT NOT NULL REFERENCES decks (id) ON DELETE CASCADE,
67
+ user_id TEXT NOT NULL,
68
+ position INTEGER NOT NULL DEFAULT 0,
69
+ front TEXT NOT NULL,
70
+ back TEXT NOT NULL,
71
+ source TEXT NOT NULL DEFAULT 'notes',
72
+ due_at BIGINT NOT NULL,
73
+ interval_days DOUBLE PRECISION NOT NULL DEFAULT 0,
74
+ ease DOUBLE PRECISION NOT NULL DEFAULT 2.5,
75
+ reps INTEGER NOT NULL DEFAULT 0,
76
+ lapses INTEGER NOT NULL DEFAULT 0
77
+ );
78
+ CREATE INDEX IF NOT EXISTS cards_user_due ON cards (user_id, due_at);
79
+ CREATE INDEX IF NOT EXISTS cards_deck_id ON cards (deck_id);
80
+
81
+ CREATE TABLE IF NOT EXISTS quiz_results (
82
+ user_id TEXT NOT NULL,
83
+ path TEXT NOT NULL,
84
+ correct INTEGER NOT NULL DEFAULT 0,
85
+ total INTEGER NOT NULL DEFAULT 0,
86
+ updated_at BIGINT NOT NULL,
87
+ PRIMARY KEY (user_id, path)
88
+ );
89
+
90
+ CREATE TABLE IF NOT EXISTS exams (
91
+ id TEXT PRIMARY KEY,
92
+ user_id TEXT NOT NULL,
93
+ course TEXT NOT NULL,
94
+ exam_date DATE NOT NULL,
95
+ plan JSONB NOT NULL,
96
+ created_at BIGINT NOT NULL
97
+ );
98
+ CREATE INDEX IF NOT EXISTS exams_user_id ON exams (user_id);
99
+
100
+ CREATE TABLE IF NOT EXISTS usage_daily (
101
+ user_id TEXT NOT NULL,
102
+ day DATE NOT NULL,
103
+ questions BIGINT NOT NULL DEFAULT 0,
104
+ uploads BIGINT NOT NULL DEFAULT 0,
105
+ pages_read BIGINT NOT NULL DEFAULT 0,
106
+ upload_failures BIGINT NOT NULL DEFAULT 0,
107
+ study_requests BIGINT NOT NULL DEFAULT 0,
108
+ reviews BIGINT NOT NULL DEFAULT 0,
109
+ prompt_tokens BIGINT NOT NULL DEFAULT 0,
110
+ completion_tokens BIGINT NOT NULL DEFAULT 0,
111
+ ratings_up BIGINT NOT NULL DEFAULT 0,
112
+ ratings_down BIGINT NOT NULL DEFAULT 0,
113
+ PRIMARY KEY (user_id, day)
114
+ );
115
+ CREATE INDEX IF NOT EXISTS usage_daily_day ON usage_daily (day);
116
+
117
+ CREATE TABLE IF NOT EXISTS feedback (
118
+ id TEXT PRIMARY KEY,
119
+ user_id TEXT NOT NULL,
120
+ kind TEXT NOT NULL,
121
+ rating TEXT NOT NULL DEFAULT '',
122
+ selection_stage TEXT NOT NULL DEFAULT '',
123
+ comment TEXT NOT NULL DEFAULT '',
124
+ question TEXT NOT NULL DEFAULT '',
125
+ answer TEXT NOT NULL DEFAULT '',
126
+ sources TEXT NOT NULL DEFAULT '',
127
+ created_at BIGINT NOT NULL
128
+ );
129
+ CREATE INDEX IF NOT EXISTS feedback_created_at ON feedback (created_at);
130
+ CREATE INDEX IF NOT EXISTS feedback_user_id ON feedback (user_id);
131
+
132
+ CREATE TABLE IF NOT EXISTS onenote_tokens (
133
+ user_id TEXT PRIMARY KEY,
134
+ token JSONB NOT NULL,
135
+ expires_at BIGINT NOT NULL DEFAULT 0
136
+ );
137
+
138
+ CREATE TABLE IF NOT EXISTS onenote_oauth_states (
139
+ state TEXT PRIMARY KEY,
140
+ user_id TEXT NOT NULL,
141
+ expires_at BIGINT NOT NULL
142
+ );
143
+
144
+ CREATE TABLE IF NOT EXISTS library_files (
145
+ path TEXT PRIMARY KEY,
146
+ subject TEXT NOT NULL,
147
+ etag TEXT NOT NULL DEFAULT '',
148
+ status TEXT NOT NULL, -- ok | empty | failed | pending
149
+ details JSONB NOT NULL DEFAULT '{}'::jsonb, -- size, pages, OCR counts, method, error, ...
150
+ content TEXT NOT NULL DEFAULT '', -- full text, used by the study tools
151
+ updated_at BIGINT NOT NULL
152
+ );
153
+ """
154
+
155
+ APP_TABLES = (
156
+ "cards", "decks", "quiz_results", "exams", "usage_daily", "feedback",
157
+ "onenote_tokens", "onenote_oauth_states", "documents", "folders", "library_files", "users",
158
+ )
159
+
160
+ _engine: Engine | None = None
161
+ _async_engine = None
162
+ _engine_lock = threading.Lock()
163
+ _init_lock = threading.Lock() # separate from _engine_lock: init() creates the engine while holding it
164
+ _ready = False
165
+
166
+
167
+ def _url(driver: str) -> str:
168
+ raw = settings.DATABASE_URL
169
+ if not raw:
170
+ raise RuntimeError("DATABASE_URL is not set. See DEPLOYMENT.md (Postgres with pgvector).")
171
+ for prefix in ("postgresql+psycopg2://", "postgresql+asyncpg://", "postgresql://", "postgres://"):
172
+ if raw.startswith(prefix):
173
+ return f"postgresql+{driver}://" + raw[len(prefix):]
174
+ raise RuntimeError("DATABASE_URL must start with postgresql:// (or postgres://).")
175
+
176
+
177
+ def engine() -> Engine:
178
+ """The shared connection pool (created on first use)."""
179
+ global _engine
180
+ if _engine is None:
181
+ with _engine_lock:
182
+ if _engine is None:
183
+ # pre_ping: free hosts (Neon, Supabase) close idle connections; check before reuse.
184
+ _engine = create_engine(
185
+ _url("psycopg2"), pool_pre_ping=True, pool_size=5, max_overflow=10, pool_recycle=1800
186
+ )
187
+ return _engine
188
+
189
+
190
+ def async_engine():
191
+ """LlamaIndex's vector store wants an async engine as well; Study AI itself never uses it."""
192
+ global _async_engine
193
+ if _async_engine is None:
194
+ with _engine_lock:
195
+ if _async_engine is None:
196
+ from sqlalchemy.ext.asyncio import create_async_engine
197
+
198
+ url = _url("asyncpg").split("?", 1)[0] # asyncpg doesn't take libpq options like sslmode
199
+ _async_engine = create_async_engine(url)
200
+ return _async_engine
201
+
202
+
203
+ def init() -> None:
204
+ """Create the pgvector extension and the tables if they don't exist yet (safe to repeat)."""
205
+ global _ready
206
+ if _ready:
207
+ return
208
+ with _init_lock:
209
+ if _ready:
210
+ return
211
+ with engine().begin() as conn:
212
+ conn.exec_driver_sql(SCHEMA)
213
+ _ready = True
214
+
215
+
216
+ @contextmanager
217
+ def transaction():
218
+ """A connection whose statements all succeed or all roll back together."""
219
+ init()
220
+ with engine().begin() as conn:
221
+ yield conn
222
+
223
+
224
+ def execute(sql: str, conn: Connection | None = None, **params) -> int:
225
+ """Run a statement; returns the number of rows it changed."""
226
+ if conn is not None:
227
+ return conn.execute(text(sql), params).rowcount
228
+ with transaction() as c:
229
+ return c.execute(text(sql), params).rowcount
230
+
231
+
232
+ def rows(sql: str, conn: Connection | None = None, **params) -> list[dict]:
233
+ if conn is not None:
234
+ return [dict(r._mapping) for r in conn.execute(text(sql), params)]
235
+ with transaction() as c:
236
+ return [dict(r._mapping) for r in c.execute(text(sql), params)]
237
+
238
+
239
+ def one(sql: str, conn: Connection | None = None, **params) -> dict | None:
240
+ found = rows(sql, conn, **params)
241
+ return found[0] if found else None
242
+
243
+
244
+ def scalar(sql: str, conn: Connection | None = None, **params):
245
+ found = one(sql, conn, **params)
246
+ return next(iter(found.values())) if found else None
247
+
248
+
249
+ def table_exists(name: str) -> bool:
250
+ return bool(scalar("SELECT to_regclass(:name) IS NOT NULL AS ok", name=f"public.{name}"))
251
+
252
+
253
+ def empty_all_tables() -> None:
254
+ """Delete every row (tests use this between cases). Passage tables are emptied too."""
255
+ init()
256
+ extra = [t for t in ("data_notes", "data_library") if table_exists(t)]
257
+ with engine().begin() as conn:
258
+ conn.exec_driver_sql("TRUNCATE " + ", ".join((*APP_TABLES, *extra)) + " CASCADE")
backend/extract_api.py DELETED
@@ -1,10 +0,0 @@
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 CHANGED
@@ -1,45 +1,38 @@
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"])
 
1
+ """Answer ratings and general feedback from students (the feedback table)."""
 
2
  import time
3
  import uuid
4
 
5
+ from backend import db
6
 
7
  KINDS = ("answer", "general")
8
  RATINGS = ("up", "down", "")
9
  _FIELD_LIMITS = {"comment": 2000, "question": 1000, "answer": 2000, "sources": 1000}
10
 
11
 
 
 
 
 
12
  def add(user_id: str, kind: str, rating: str, selection_stage: str = "", **fields: str) -> None:
13
+ texts = {k: str(fields.get(k) or "")[:limit] for k, limit in _FIELD_LIMITS.items()}
14
+ db.execute(
15
+ "INSERT INTO feedback (id, user_id, kind, rating, selection_stage, comment, question, answer, sources, "
16
+ "created_at) VALUES (:id, :u, :kind, :rating, :stage, :comment, :question, :answer, :sources, :now)",
17
+ id=f"fb_{uuid.uuid4().hex}",
18
+ u=user_id,
19
+ kind=kind,
20
+ rating=rating,
21
+ stage=(selection_stage or "")[:40],
22
+ now=int(time.time()),
23
+ **texts,
 
24
  )
25
 
26
 
27
  def recent(limit: int = 50, since: int = 0) -> list[dict]:
28
+ found = db.rows(
29
+ "SELECT user_id, kind, rating, selection_stage, comment, question, answer, sources, created_at "
30
+ "FROM feedback WHERE created_at >= :since ORDER BY created_at DESC LIMIT :limit",
31
+ since=int(since),
32
+ limit=int(limit),
33
+ )
34
+ return [{**r, "created_at": int(r["created_at"])} for r in found]
35
 
36
 
37
  def delete_user(user_id: str) -> None:
38
+ db.execute("DELETE FROM feedback WHERE user_id = :u", u=user_id)
 
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 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]]:
 
1
+ """Per-user file details (main source, related paths), stored with the folder tree (folders table)."""
2
  from typing import Any
3
 
4
+ from backend.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]]:
backend/ingest_api.py DELETED
@@ -1,185 +0,0 @@
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):
46
- splitter = RecursiveCharacterTextSplitter(chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)
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),
73
- "path": str(path or ""),
74
- "source_file": str(source_file or ""),
75
- "course_id": str(course_id_from_path(path)),
76
- "is_primary_authority": int(bool(fm.get("is_primary_authority"))),
77
- "doc_type": str(fm.get("doc_type") or "other"),
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:
104
- """Update metadata on existing chunks (e.g. after toggling primary authority)."""
105
- if not chroma_paths:
106
- return 0
107
- col = get_user_collection(user_id)
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"])
164
- except (TypeError, ValueError):
165
- m["chunk_index"] = k
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 DELETED
@@ -1,86 +0,0 @@
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 CHANGED
@@ -2,12 +2,13 @@
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 Interview.ai; 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
@@ -18,6 +19,7 @@ admin endpoint, or every LIBRARY_SYNC_HOURS.
18
  """
19
  import bisect
20
  import io
 
21
  import logging
22
  import threading
23
  import time
@@ -28,23 +30,10 @@ 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
@@ -113,39 +102,21 @@ def label_of(path: str) -> str:
113
  return " › ".join(x for x in (subject, folder, name) if x)
114
 
115
 
116
- def _doc_id(path: str) -> str:
117
- return short_id("libdoc", path)
118
-
119
-
120
- def _chunk_id_base(path: str) -> str:
121
- return short_id("lib", path)
122
-
123
-
124
- # ---------- Collections ----------
125
- def _notes(create: bool):
126
- return _get_or_create_collection(NOTES_COLLECTION) if create else _get_collection_or_none(NOTES_COLLECTION)
127
-
128
-
129
- def _docs(create: bool):
130
- return _get_or_create_collection(DOCS_COLLECTION) if create else _get_collection_or_none(DOCS_COLLECTION)
131
-
132
-
133
  def indexed_files() -> dict[str, dict]:
134
  """{path: details} for every PDF the library knows about (any status)."""
135
- col = _docs(create=False)
136
- if col is None:
137
- return {}
138
- res = get_all(col, where={"kind": "library_file"}, include=["metadatas"])
139
- return {m["path"]: m for m in res.get("metadatas") or [] if m and m.get("path")}
 
140
 
141
 
142
  def document_text(path: str) -> str:
143
  """Full text read from a library PDF ("" if it isn't indexed)."""
144
- col = _docs(create=False)
145
- if col is None:
146
- return ""
147
  try:
148
- return (_read_parts(col, _doc_id(path)) or "").strip()
149
  except Exception:
150
  logger.warning("Could not read library text for %s", path, exc_info=True)
151
  return ""
@@ -229,7 +200,7 @@ class PdfText:
229
  def _ocr_mode() -> str:
230
  mode = settings.LIBRARY_OCR
231
  if mode == "auto":
232
- return "sarvam" if llm_pipeline._sarvam_api_key() else "tesseract"
233
  return mode if mode in ("sarvam", "tesseract", "off") else "tesseract"
234
 
235
 
@@ -332,7 +303,7 @@ def _sarvam_batch(tiles: list[Tile]) -> list[str] | None:
332
  pdf = doc.tobytes()
333
  finally:
334
  doc.close()
335
- text, err, page_texts = llm_pipeline.transcribe_pdf_with_pages(pdf)
336
  if err or not (text or "").strip():
337
  logger.warning("Sarvam Vision failed for a library batch: %s", err or "empty output")
338
  return None
@@ -435,114 +406,80 @@ def _chunks_with_positions(
435
  Passages with the page and spot (0..1) each one starts at. Inside a piece the spot is estimated
436
  from how far into the piece's text the passage starts (writing runs top to bottom).
437
  """
438
- from langchain_text_splitters import RecursiveCharacterTextSplitter
439
-
440
- from backend.ingest_api import CHUNK_OVERLAP, CHUNK_SIZE
441
 
442
- splitter = RecursiveCharacterTextSplitter(chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP, add_start_index=True)
443
  offsets = [a[0] for a in anchors]
444
  out = []
445
- for d in splitter.create_documents([text]):
446
  if not anchors:
447
- out.append((d.page_content, None, None))
448
  continue
449
- start = max(int(d.metadata.get("start_index") or 0), 0)
450
  i = max(bisect.bisect_right(offsets, start) - 1, 0)
451
  piece_start, page, y0, y1 = anchors[i]
452
  piece_end = offsets[i + 1] if i + 1 < len(offsets) else len(text)
453
  share = min(max((start - piece_start) / max(piece_end - piece_start, 1), 0.0), 1.0)
454
- out.append((d.page_content, page, y0 + share * (y1 - y0)))
455
  return out
456
 
457
 
458
- def _file_meta(entry: dict, status: str, **extra) -> dict:
459
  path = entry["path"]
460
- return {
461
- "path": path,
462
- "subject": subject_of(path),
463
- "etag": entry.get("etag") or "",
464
- "size": int(entry.get("size") or 0),
465
- "status": status,
466
- "updated_at": int(time.time()),
467
- **extra,
468
- }
 
 
 
 
 
469
 
470
 
471
  def _store(entry: dict, pdf: PdfText) -> int:
472
  """Replace the passages and stored text of one PDF. Returns the number of passages."""
473
- from backend.ingest_api import embed_texts
474
 
475
  path = entry["path"]
476
- col = _notes(create=True)
477
- old_ids = get_all(col, where={"path": path}, include=[])["ids"]
478
- chunks = _chunks_with_positions(pdf.text, pdf.anchors)
479
  base = {
480
- "path": path,
481
  "subject": subject_of(path),
482
  "source_file": path.rsplit("/", 1)[-1],
483
  "label": label_of(path),
484
  "pages": int(pdf.pages),
485
  "library": 1,
486
  }
487
- new_ids: list[str] = []
488
- for i in range(0, len(chunks), 50):
489
- batch = chunks[i : i + 50]
490
- ids = [f"{_chunk_id_base(path)}_{i + j}" for j in range(len(batch))]
491
- metas = []
492
- for j, (_, page, y) in enumerate(batch):
493
- m = {**base, "chunk_index": i + j}
494
- if page is not None:
495
- m["page"] = int(page)
496
- if y is not None:
497
- m["y"] = round(float(y), 4)
498
- metas.append(m)
499
- col.upsert(
500
- ids=ids,
501
- documents=[c[0] for c in batch],
502
- embeddings=embed_texts([c[0] for c in batch]).tolist(),
503
- metadatas=metas,
504
- )
505
- new_ids.extend(ids)
506
- keep = set(new_ids)
507
- delete_ids(col, [x for x in old_ids if x not in keep])
508
- _write_parts(
509
- _docs(create=True),
510
- _doc_id(path),
511
  pdf.text,
512
- "library_file",
513
- _file_meta(
514
- entry,
515
- "ok",
516
- pages=pdf.pages,
517
- ocr_pieces=pdf.ocr_pieces,
518
- sarvam_pieces=pdf.sarvam_pieces,
519
- chunks=len(chunks),
520
- chars=len(pdf.text),
521
- method=pdf.method,
522
- note=",".join(sorted(set(pdf.notes))),
523
- ),
524
  )
525
- return len(chunks)
526
 
527
 
528
  def _store_status(entry: dict, status: str, error: str = "") -> None:
529
  """Record a PDF that couldn't be indexed (yet), keeping any passages from an earlier version."""
530
- _write_parts(_docs(create=True), _doc_id(entry["path"]), "", "library_file", _file_meta(entry, status, error=error[:300]))
531
 
532
 
533
  def remove(path: str) -> None:
534
- col = _notes(create=False)
535
- if col is not None:
536
- delete_ids(col, get_all(col, where={"path": path}, include=[])["ids"])
537
- docs = _docs(create=False)
538
- if docs is None:
539
- return
540
- doc_id = _doc_id(path)
541
- res = docs.get(ids=[doc_id], include=["metadatas"])
542
- if res.get("ids"):
543
- meta = (res.get("metadatas") or [{}])[0] or {}
544
- parts, version = int(meta.get("parts") or 0), str(meta.get("version") or "")
545
- delete_ids(docs, [f"{doc_id}#{version}#{k}" for k in range(parts)] + [doc_id])
546
 
547
 
548
  # ---------- Sync ----------
@@ -718,41 +655,7 @@ def public_status() -> dict:
718
  return {"enabled": True, "ready": list(_status_cache["value"]), "syncing": bool(_state["running"])}
719
 
720
 
721
- # ---------- Search + study context ----------
722
- def search(q_emb: list[float], where: dict, n_results: int) -> list[dict]:
723
- """Best library passages matching `where`, scored as cosine similarity (same scale as notes)."""
724
- if not settings.LIBRARY_ENABLED:
725
- return []
726
- col = _notes(create=False)
727
- if col is None:
728
- return []
729
- try:
730
- res = col.query(
731
- query_embeddings=[q_emb],
732
- n_results=n_results,
733
- include=["documents", "metadatas", "distances"],
734
- where=where,
735
- )
736
- except Exception:
737
- logger.warning("Library search failed", exc_info=True)
738
- return []
739
- space = collection_distance_space(col)
740
- ids = (res.get("ids") or [[]])[0] or []
741
- docs = (res.get("documents") or [[]])[0] or []
742
- metas = (res.get("metadatas") or [[]])[0] or []
743
- dists = (res.get("distances") or [[]])[0] or []
744
- out = []
745
- for i, cid in enumerate(ids):
746
- content = (docs[i] if i < len(docs) else "") or ""
747
- if not content.strip():
748
- continue
749
- md = metas[i] if i < len(metas) and isinstance(metas[i], dict) else {}
750
- dist = float(dists[i]) if i < len(dists) and dists[i] is not None else 2.0
751
- out.append({"id": cid, "content": content, "metadata": md, "_score": distance_to_similarity(dist, space)})
752
- out.sort(key=lambda d: d["_score"], reverse=True)
753
- return out
754
-
755
-
756
  def study_context(library_path: str, focus: str, include_subject: bool) -> tuple[str | None, str | None]:
757
  """Study-tool context from a library PDF (plus short parts of its course), like the notes version."""
758
  file_path, subject = scope_of(library_path)
 
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 Interview.ai; see LIBRARY_* in
5
+ settings.py). They are stored once and shared, so nothing is copied per student:
6
 
7
+ - data_library search passages + fingerprints (pipeline/indexing.py); metadata: path, subject,
8
+ page and `y` (where on the page the passage starts, 0 = top, 1 = bottom) so a
9
+ viewer can scroll to it
10
+ - library_files one row per PDF (eTag, status, page counts) plus its full text, which the study
11
+ tools read
12
 
13
  sync() brings the index in line with the bucket: new or changed PDFs (by eTag) are read and
14
  indexed, removed ones are deleted. Pages that contain real text are read with PyMuPDF. Handwritten
 
19
  """
20
  import bisect
21
  import io
22
+ import json
23
  import logging
24
  import threading
25
  import time
 
30
  import numpy as np
31
  from fastapi import HTTPException
32
 
33
+ from backend import db, ocr, settings, usage
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  logger = logging.getLogger(__name__)
36
 
 
 
37
  USAGE_ID = "library" # usage counters for pages the library sent to Sarvam (cost on the admin page)
38
  OCR_BATCH = 10 # Sarvam Vision reads at most 10 pages per job
39
  MIN_FILE_BYTES = 1000 # smaller "PDFs" in the bucket are empty placeholders
 
102
  return " › ".join(x for x in (subject, folder, name) if x)
103
 
104
 
105
+ # ---------- Stored files ----------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  def indexed_files() -> dict[str, dict]:
107
  """{path: details} for every PDF the library knows about (any status)."""
108
+ found = db.rows("SELECT path, subject, etag, status, details, updated_at FROM library_files")
109
+ return {
110
+ r["path"]: {**(r["details"] or {}), "path": r["path"], "subject": r["subject"], "etag": r["etag"],
111
+ "status": r["status"], "updated_at": int(r["updated_at"])}
112
+ for r in found
113
+ }
114
 
115
 
116
  def document_text(path: str) -> str:
117
  """Full text read from a library PDF ("" if it isn't indexed)."""
 
 
 
118
  try:
119
+ return (db.scalar("SELECT content FROM library_files WHERE path = :p", p=path) or "").strip()
120
  except Exception:
121
  logger.warning("Could not read library text for %s", path, exc_info=True)
122
  return ""
 
200
  def _ocr_mode() -> str:
201
  mode = settings.LIBRARY_OCR
202
  if mode == "auto":
203
+ return "sarvam" if ocr.sarvam_api_key() else "tesseract"
204
  return mode if mode in ("sarvam", "tesseract", "off") else "tesseract"
205
 
206
 
 
303
  pdf = doc.tobytes()
304
  finally:
305
  doc.close()
306
+ text, err, page_texts = ocr.transcribe_pdf_with_pages(pdf)
307
  if err or not (text or "").strip():
308
  logger.warning("Sarvam Vision failed for a library batch: %s", err or "empty output")
309
  return None
 
406
  Passages with the page and spot (0..1) each one starts at. Inside a piece the spot is estimated
407
  from how far into the piece's text the passage starts (writing runs top to bottom).
408
  """
409
+ from backend.pipeline.indexing import split_text, text_start
 
 
410
 
 
411
  offsets = [a[0] for a in anchors]
412
  out = []
413
+ for chunk, start in split_text(text):
414
  if not anchors:
415
+ out.append((chunk, None, None))
416
  continue
417
+ start = max(text_start(chunk, int(start)), 0)
418
  i = max(bisect.bisect_right(offsets, start) - 1, 0)
419
  piece_start, page, y0, y1 = anchors[i]
420
  piece_end = offsets[i + 1] if i + 1 < len(offsets) else len(text)
421
  share = min(max((start - piece_start) / max(piece_end - piece_start, 1), 0.0), 1.0)
422
+ out.append((chunk, page, y0 + share * (y1 - y0)))
423
  return out
424
 
425
 
426
+ def _save_file(entry: dict, status: str, text: str = "", **details) -> None:
427
  path = entry["path"]
428
+ db.execute(
429
+ "INSERT INTO library_files (path, subject, etag, status, details, content, updated_at) "
430
+ "VALUES (:p, :subject, :etag, :status, CAST(:details AS jsonb), :content, :now) "
431
+ "ON CONFLICT (path) DO UPDATE SET subject = EXCLUDED.subject, etag = EXCLUDED.etag, "
432
+ "status = EXCLUDED.status, details = EXCLUDED.details, content = EXCLUDED.content, "
433
+ "updated_at = EXCLUDED.updated_at",
434
+ p=path,
435
+ subject=subject_of(path),
436
+ etag=entry.get("etag") or "",
437
+ status=status,
438
+ details=json.dumps({"size": int(entry.get("size") or 0), **details}),
439
+ content=(text or "").replace("\x00", ""),
440
+ now=int(time.time()),
441
+ )
442
 
443
 
444
  def _store(entry: dict, pdf: PdfText) -> int:
445
  """Replace the passages and stored text of one PDF. Returns the number of passages."""
446
+ from backend.pipeline.indexing import index_library_file
447
 
448
  path = entry["path"]
449
+ pieces = _chunks_with_positions(pdf.text, pdf.anchors)
 
 
450
  base = {
 
451
  "subject": subject_of(path),
452
  "source_file": path.rsplit("/", 1)[-1],
453
  "label": label_of(path),
454
  "pages": int(pdf.pages),
455
  "library": 1,
456
  }
457
+ count = index_library_file(path, base, pieces)
458
+ _save_file(
459
+ entry,
460
+ "ok",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
  pdf.text,
462
+ pages=pdf.pages,
463
+ ocr_pieces=pdf.ocr_pieces,
464
+ sarvam_pieces=pdf.sarvam_pieces,
465
+ chunks=count,
466
+ chars=len(pdf.text),
467
+ method=pdf.method,
468
+ note=",".join(sorted(set(pdf.notes))),
 
 
 
 
 
469
  )
470
+ return count
471
 
472
 
473
  def _store_status(entry: dict, status: str, error: str = "") -> None:
474
  """Record a PDF that couldn't be indexed (yet), keeping any passages from an earlier version."""
475
+ _save_file(entry, status, "", error=error[:300])
476
 
477
 
478
  def remove(path: str) -> None:
479
+ from backend.pipeline.indexing import delete_library_file
480
+
481
+ delete_library_file(path)
482
+ db.execute("DELETE FROM library_files WHERE path = :p", p=path)
 
 
 
 
 
 
 
 
483
 
484
 
485
  # ---------- Sync ----------
 
655
  return {"enabled": True, "ready": list(_status_cache["value"]), "syncing": bool(_state["running"])}
656
 
657
 
658
+ # ---------- Study context ----------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
659
  def study_context(library_path: str, focus: str, include_subject: bool) -> tuple[str | None, str | None]:
660
  """Study-tool context from a library PDF (plus short parts of its course), like the notes version."""
661
  file_path, subject = scope_of(library_path)
backend/mailer.py CHANGED
@@ -1,4 +1,5 @@
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
@@ -37,11 +38,3 @@ def send_email(to: str, subject: str, body: str) -> None:
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)
 
1
+ """Sending review-reminder emails over SMTP. Enabled only when SMTP_HOST and SMTP_FROM are set.
2
+ (Password-reset and email-check emails are sent by Neon Auth.)"""
3
  import logging
4
  import os
5
  import smtplib
 
38
  smtp.login(username, password)
39
  smtp.send_message(msg)
40
 
 
 
 
 
 
 
 
 
backend/neon_auth.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Sign-in through Neon Auth (Managed Better Auth, https://neon.com/docs/auth/overview).
3
+
4
+ Neon keeps the accounts and passwords and sends the password-reset and email-check emails. The
5
+ browser never talks to Neon itself: this server does, and hands the website the sign-in (Neon's
6
+ session cookie value), which the website sends back as the X-Session-Id header. That way sign-in
7
+ doesn't depend on browsers accepting another site's cookies (Safari blocks them), and Interview.ai's
8
+ "Ask AI" panel keeps working with the same header.
9
+
10
+ Neon only accepts changes from trusted websites, so every request carries the Origin of FRONTEND_URL:
11
+ add that website under Neon Console -> Auth -> Domains (localhost is allowed by default).
12
+
13
+ When Neon is set to require confirmed emails, a new account gets no sign-in until the student enters
14
+ the code Neon emails them; confirming the code signs them in (verify_email).
15
+ """
16
+ import hashlib
17
+ import http.cookiejar
18
+ import logging
19
+ import re
20
+ import threading
21
+ import time
22
+ from dataclasses import dataclass
23
+ from urllib.parse import urlsplit
24
+
25
+ import httpx
26
+
27
+ from backend import db, settings
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ COOKIE = "__Secure-neon-auth.session_token"
32
+ # What a session id (Neon's signed cookie value) can contain; anything else could smuggle extra cookies.
33
+ _SESSION_RE = re.compile(r"^[A-Za-z0-9._~%+/=-]{16,512}$")
34
+
35
+ # Tests plug in new_client(fake transport) here; None = a client for the real service.
36
+ HTTP_CLIENT = None
37
+ _client = None
38
+ _client_lock = threading.Lock()
39
+
40
+ # Checking a sign-in with Neon takes a request to Neon; remember the answer for a short while.
41
+ _cache: dict[str, tuple[float, "User | None"]] = {}
42
+ _cache_lock = threading.Lock()
43
+ _CACHE_MAX = 10000
44
+ _UNKNOWN_SECONDS = 5
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class User:
49
+ id: str
50
+ email: str
51
+ name: str
52
+ email_verified: bool
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class SignIn:
57
+ session: str # what the website keeps and sends back as X-Session-Id ("" until the email is confirmed)
58
+ user: User
59
+
60
+
61
+ class AuthError(Exception):
62
+ """A sign-in request Neon refused or couldn't answer; `message` is shown to the user."""
63
+
64
+ def __init__(self, message: str, status: int = 400, code: str = ""):
65
+ super().__init__(message)
66
+ self.message = message
67
+ self.status = status
68
+ self.code = code
69
+
70
+
71
+ UNAVAILABLE = "Can't reach the sign-in service right now. Please try again in a moment."
72
+
73
+
74
+ def configured() -> bool:
75
+ return bool(settings.NEON_AUTH_BASE_URL)
76
+
77
+
78
+ class _NoCookies(http.cookiejar.DefaultCookiePolicy):
79
+ def set_ok(self, cookie, request):
80
+ return False
81
+
82
+
83
+ def new_client(transport: httpx.BaseTransport | None = None) -> httpx.Client:
84
+ """
85
+ A client that never keeps cookies: it is shared by every student's requests, so a kept session
86
+ cookie would be sent along with someone else's request. Each reply's cookies are still readable.
87
+ """
88
+ return httpx.Client(timeout=20, transport=transport, cookies=http.cookiejar.CookieJar(policy=_NoCookies()))
89
+
90
+
91
+ def _http() -> httpx.Client:
92
+ global _client
93
+ if HTTP_CLIENT is not None:
94
+ return HTTP_CLIENT
95
+ with _client_lock:
96
+ if _client is None:
97
+ _client = new_client()
98
+ return _client
99
+
100
+
101
+ def _origin() -> str:
102
+ parts = urlsplit(settings.FRONTEND_URL)
103
+ return f"{parts.scheme}://{parts.netloc}"
104
+
105
+
106
+ def _request(path: str, payload: dict | None = None, session: str | None = None, method: str = "POST") -> httpx.Response:
107
+ if not configured():
108
+ raise AuthError("Sign-in isn't set up on this server (NEON_AUTH_BASE_URL).", 503, "NOT_CONFIGURED")
109
+ headers = {"Origin": _origin()}
110
+ if session:
111
+ if not _SESSION_RE.match(session):
112
+ raise AuthError("Your session has expired. Please sign in again.", 401, "BAD_SESSION")
113
+ headers["Cookie"] = f"{COOKIE}={session}"
114
+ url = settings.NEON_AUTH_BASE_URL.rstrip("/") + path
115
+ try:
116
+ if method == "GET":
117
+ return _http().get(url, headers=headers)
118
+ return _http().post(url, json=payload if payload is not None else {}, headers=headers)
119
+ except httpx.HTTPError as e:
120
+ logger.warning("Neon Auth %s failed: %s", path, e)
121
+ raise AuthError(UNAVAILABLE, 503, "UNAVAILABLE") from e
122
+
123
+
124
+ def _body(r: httpx.Response) -> dict:
125
+ try:
126
+ data = r.json()
127
+ except ValueError:
128
+ return {}
129
+ return data if isinstance(data, dict) else {}
130
+
131
+
132
+ def _check(r: httpx.Response, messages: dict[str, tuple[str, int]]) -> dict:
133
+ """The JSON body of a successful reply; otherwise AuthError with a readable message."""
134
+ body = _body(r)
135
+ if r.status_code < 400:
136
+ return body
137
+ code = str(body.get("code") or "")
138
+ if code in messages:
139
+ message, status = messages[code]
140
+ raise AuthError(message, status, code)
141
+ if r.status_code == 429:
142
+ raise AuthError("Too many attempts. Please wait a minute and try again.", 429, code)
143
+ if code in ("INVALID_ORIGIN", "MISSING_OR_NULL_ORIGIN", "INVALID_REDIRECT_URL", "INVALID_CALLBACKURL"):
144
+ logger.error("Neon Auth refused %s: add it under Neon Console -> Auth -> Domains", _origin())
145
+ raise AuthError("Sign-in isn't set up correctly on this server.", 503, code)
146
+ if r.status_code >= 500:
147
+ raise AuthError(UNAVAILABLE, 503, code)
148
+ logger.warning("Neon Auth refused a request: %s %s", r.status_code, body)
149
+ raise AuthError(str(body.get("message") or "The sign-in service refused the request."), 400, code)
150
+
151
+
152
+ def _user(data: dict) -> User:
153
+ return User(
154
+ id=str(data.get("id") or ""),
155
+ email=str(data.get("email") or "").lower(),
156
+ name=str(data.get("name") or ""),
157
+ email_verified=bool(data.get("emailVerified")),
158
+ )
159
+
160
+
161
+ def _signed_in(r: httpx.Response, body: dict, need_session: bool = True) -> SignIn:
162
+ session = r.cookies.get(COOKIE) or ""
163
+ user = body.get("user")
164
+ if not isinstance(user, dict) or not (session or not need_session):
165
+ logger.error("Neon Auth reply had no session cookie or user")
166
+ raise AuthError(UNAVAILABLE, 503, "NO_SESSION")
167
+ return SignIn(session=session, user=_user(user))
168
+
169
+
170
+ # ---------- Accounts and sign-ins ----------
171
+ def sign_up(email: str, password: str, name: str) -> SignIn:
172
+ """The new account, signed in; or with session "" when Neon wants the email confirmed first (it has
173
+ emailed the code)."""
174
+ r = _request("/sign-up/email", {"email": email, "password": password, "name": name})
175
+ body = _check(r, {
176
+ "USER_ALREADY_EXISTS": ("Email already registered.", 400),
177
+ "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL": ("Email already registered.", 400),
178
+ "INVALID_EMAIL": ("Please enter a valid email address.", 400),
179
+ "PASSWORD_TOO_SHORT": (f"Password must be at least {settings.MIN_PASSWORD_LEN} characters.", 400),
180
+ "PASSWORD_TOO_LONG": ("Password is too long.", 400),
181
+ })
182
+ return _signed_in(r, body, need_session=False)
183
+
184
+
185
+ def sign_in(email: str, password: str) -> SignIn:
186
+ """Raises AuthError code EMAIL_NOT_VERIFIED (only after a correct password) while the email isn't confirmed."""
187
+ r = _request("/sign-in/email", {"email": email, "password": password})
188
+ body = _check(r, {
189
+ "INVALID_EMAIL_OR_PASSWORD": ("Invalid email or password.", 401),
190
+ "EMAIL_NOT_VERIFIED": ("Please confirm your email first.", 403),
191
+ })
192
+ return _signed_in(r, body)
193
+
194
+
195
+ def sign_out(session: str) -> None:
196
+ """End the sign-in at Neon too, so it stops working on every server."""
197
+ forget(session)
198
+ if session and _SESSION_RE.match(session):
199
+ try:
200
+ _request("/sign-out", session=session)
201
+ except AuthError:
202
+ logger.warning("Couldn't end a session at Neon Auth", exc_info=True)
203
+
204
+
205
+ def change_password(session: str, current: str, new: str) -> str:
206
+ """Change the password and sign out every other device. Returns this device's new sign-in."""
207
+ r = _request(
208
+ "/change-password",
209
+ {"currentPassword": current, "newPassword": new, "revokeOtherSessions": True},
210
+ session=session,
211
+ )
212
+ _check(r, {
213
+ "INVALID_PASSWORD": ("Your current password is incorrect.", 400),
214
+ "PASSWORD_TOO_SHORT": (f"Password must be at least {settings.MIN_PASSWORD_LEN} characters.", 400),
215
+ "PASSWORD_TOO_LONG": ("Password is too long.", 400),
216
+ })
217
+ forget(session)
218
+ return r.cookies.get(COOKIE) or session
219
+
220
+
221
+ def request_password_reset(email: str, redirect_to: str) -> None:
222
+ """Neon emails a reset link (if the account exists) that leads back to `redirect_to` with ?token=."""
223
+ _check(_request("/request-password-reset", {"email": email, "redirectTo": redirect_to}), {})
224
+
225
+
226
+ def reset_password(token: str, new_password: str) -> None:
227
+ r = _request("/reset-password", {"token": token, "newPassword": new_password})
228
+ _check(r, {
229
+ "INVALID_TOKEN": ("This reset link is invalid or has expired. Please ask for a new one.", 400),
230
+ "PASSWORD_TOO_SHORT": (f"Password must be at least {settings.MIN_PASSWORD_LEN} characters.", 400),
231
+ "PASSWORD_TOO_LONG": ("Password is too long.", 400),
232
+ })
233
+
234
+
235
+ def send_verification_code(email: str) -> None:
236
+ """Email a code that confirms the address (if an account has it)."""
237
+ _check(_request("/email-otp/send-verification-otp", {"email": email, "type": "email-verification"}), {})
238
+
239
+
240
+ def verify_email(email: str, code: str) -> SignIn | None:
241
+ """Confirm the email with the emailed code. Neon then signs the student in: that sign-in, if any."""
242
+ r = _request("/email-otp/verify-email", {"email": email, "otp": code})
243
+ body = _check(r, {
244
+ "INVALID_OTP": ("That code is wrong. Please check the email and try again.", 400),
245
+ "OTP_EXPIRED": ("That code has expired. Please ask for a new one.", 400),
246
+ "TOO_MANY_ATTEMPTS": ("Too many wrong codes. Please ask for a new one.", 429),
247
+ })
248
+ forget_user(_user_id_for_email(email))
249
+ if r.cookies.get(COOKIE) and isinstance(body.get("user"), dict):
250
+ return _signed_in(r, body)
251
+ return None
252
+
253
+
254
+ def revoke_sessions(session: str) -> None:
255
+ """Sign out every device of the session's user."""
256
+ _check(_request("/revoke-sessions", session=session), {})
257
+
258
+
259
+ def delete_user(user_id: str) -> None:
260
+ """Delete the Neon Auth account (its sessions and password go with it). Neon Auth keeps its
261
+ accounts in the neon_auth schema of the project's own database, which DATABASE_URL points at."""
262
+ if db.scalar("SELECT to_regclass('neon_auth.\"user\"') IS NOT NULL AS ok"):
263
+ db.execute('DELETE FROM neon_auth."user" WHERE id = CAST(:id AS uuid)', id=user_id)
264
+ else: # e.g. a local database while sign-in uses Neon
265
+ logger.warning("Neon Auth account %s not deleted: delete it in the Neon Console (Auth -> Users)", user_id)
266
+ forget_user(user_id)
267
+
268
+
269
+ def _user_id_for_email(email: str) -> str:
270
+ with _cache_lock:
271
+ for _, user in _cache.values():
272
+ if user and user.email == email.lower():
273
+ return user.id
274
+ return ""
275
+
276
+
277
+ # ---------- Checking a sign-in ----------
278
+ def _key(session: str) -> str:
279
+ return hashlib.sha256(session.encode("utf-8")).hexdigest()
280
+
281
+
282
+ def current_user(session: str) -> User | None:
283
+ """The user signed in with this session, or None. Raises AuthError if Neon can't be reached."""
284
+ if not session or not _SESSION_RE.match(session):
285
+ return None
286
+ key = _key(session)
287
+ now = time.time()
288
+ with _cache_lock:
289
+ hit = _cache.get(key)
290
+ if hit and hit[0] > now:
291
+ return hit[1]
292
+ r = _request("/get-session", session=session, method="GET")
293
+ body = _check(r, {})
294
+ user = _user(body["user"]) if isinstance(body.get("user"), dict) else None
295
+ ttl = settings.AUTH_CACHE_SECONDS if user else _UNKNOWN_SECONDS
296
+ with _cache_lock:
297
+ if len(_cache) >= _CACHE_MAX:
298
+ _cache.clear()
299
+ _cache[key] = (now + ttl, user)
300
+ return user
301
+
302
+
303
+ def forget(session: str | None) -> None:
304
+ if session:
305
+ with _cache_lock:
306
+ _cache.pop(_key(session), None)
307
+
308
+
309
+ def forget_user(user_id: str) -> None:
310
+ """Drop every remembered sign-in of this user (after a password change, email check or deletion)."""
311
+ if not user_id:
312
+ return
313
+ with _cache_lock:
314
+ for key in [k for k, (_, u) in _cache.items() if u and u.id == user_id]:
315
+ del _cache[key]
316
+
317
+
318
+ def reset_cache() -> None:
319
+ with _cache_lock:
320
+ _cache.clear()
backend/ocr.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reading text out of PDFs and photos: Sarvam Vision (Sarvam AI's Document Intelligence) first,
3
+ with PyMuPDF (text already inside a PDF, see pages.py) and Tesseract (photos) as free fallbacks.
4
+ """
5
+ import io
6
+ import json
7
+ import logging
8
+ import os
9
+ import re
10
+ import tempfile
11
+ import zipfile
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def sarvam_api_key() -> str | None:
17
+ k = os.getenv("SARVAM_API_KEY")
18
+ return k.strip() if k else None
19
+
20
+
21
+ def tesseract_image_text(data: bytes) -> str:
22
+ """Local fallback for photos when Sarvam Vision is unavailable."""
23
+ import pytesseract
24
+ from PIL import Image
25
+
26
+ return pytesseract.image_to_string(Image.open(io.BytesIO(data)))
27
+
28
+
29
+ def _prepare_image_for_document_intel(image_bytes: bytes, mime: str) -> tuple[bytes, str]:
30
+ """Document Intelligence accepts PNG/JPEG/PDF; normalize webp/gif to JPEG."""
31
+ m = (mime or "image/jpeg").lower()
32
+ if m in ("image/webp", "image/gif"):
33
+ from io import BytesIO
34
+
35
+ from PIL import Image
36
+
37
+ im = Image.open(BytesIO(image_bytes)).convert("RGB")
38
+ out = BytesIO()
39
+ im.save(out, format="JPEG", quality=92)
40
+ return out.getvalue(), ".jpg"
41
+ if m == "image/png":
42
+ return image_bytes, ".png"
43
+ return image_bytes, ".jpg"
44
+
45
+
46
+ def _prepare_document_for_document_intel(file_bytes: bytes, mime: str) -> tuple[bytes, str]:
47
+ """Normalize uploads for Sarvam Document Intelligence (image or PDF)."""
48
+ m = (mime or "").lower().strip()
49
+ if m == "application/pdf":
50
+ return file_bytes, ".pdf"
51
+ return _prepare_image_for_document_intel(file_bytes, m or "image/jpeg")
52
+
53
+
54
+ # Sarvam's markdown embeds every figure it finds as a base64 image: often hundreds of KB per page,
55
+ # which would flood search with junk passages. Keep a short marker instead.
56
+ _INLINE_IMAGE_RES = (
57
+ re.compile(r"!\[[^\]]*\]\(\s*data:[^)]*\)"),
58
+ re.compile(r"<img\b[^>]*\bsrc\s*=\s*[\"']data:[^\"']*[\"'][^>]*>", re.IGNORECASE),
59
+ re.compile(r"data:image/[\w.+-]+;base64,[A-Za-z0-9+/=\s]{64,}"),
60
+ )
61
+
62
+
63
+ def strip_inline_images(text: str) -> str:
64
+ for pattern in _INLINE_IMAGE_RES:
65
+ text = pattern.sub("[figure]", text or "")
66
+ return text
67
+
68
+
69
+ def _extract_markdown_from_output_zip(zip_path: str) -> str:
70
+ with zipfile.ZipFile(zip_path, "r") as z:
71
+ names = sorted(z.namelist())
72
+ md_names = [n for n in names if n.lower().endswith(".md")]
73
+ html_names = [n for n in names if n.lower().endswith((".html", ".htm"))]
74
+ pick = (md_names[0] if md_names else None) or (html_names[0] if html_names else None) or (
75
+ names[0] if names else None
76
+ )
77
+ if not pick:
78
+ return ""
79
+ return strip_inline_images(z.read(pick).decode("utf-8", errors="replace")).strip()
80
+
81
+
82
+ def _strings_in(value) -> list[str]:
83
+ if isinstance(value, str):
84
+ return [value]
85
+ if isinstance(value, dict):
86
+ out = []
87
+ for k in ("text", "content", "markdown"):
88
+ if isinstance(value.get(k), str):
89
+ out.append(value[k])
90
+ for v in value.values():
91
+ if isinstance(v, (dict, list)):
92
+ out.extend(_strings_in(v))
93
+ return out
94
+ if isinstance(value, list):
95
+ return [s for v in value for s in _strings_in(v)]
96
+ return []
97
+
98
+
99
+ def _page_texts_from_output_zip(zip_path: str) -> list[str]:
100
+ """Per-page text from metadata/page_NNN.json files in a Document Intelligence output zip ([] if absent)."""
101
+ pages: list[tuple[int, str]] = []
102
+ try:
103
+ with zipfile.ZipFile(zip_path, "r") as z:
104
+ for name in z.namelist():
105
+ m = re.search(r"page_(\d+)\.json$", name)
106
+ if not m:
107
+ continue
108
+ try:
109
+ data = json.loads(z.read(name).decode("utf-8", errors="replace"))
110
+ except json.JSONDecodeError:
111
+ continue
112
+ pages.append((int(m.group(1)), strip_inline_images(" ".join(_strings_in(data)))))
113
+ except zipfile.BadZipFile:
114
+ return []
115
+ return [text for _, text in sorted(pages)]
116
+
117
+
118
+ def _document_intelligence(file_bytes: bytes, mime: str) -> tuple[str | None, str | None]:
119
+ text, err, _pages = _document_intelligence_with_pages(file_bytes, mime)
120
+ return text, err
121
+
122
+
123
+ def _document_intelligence_with_pages(file_bytes: bytes, mime: str) -> tuple[str | None, str | None, list[str]]:
124
+ """
125
+ OCR / layout text via Sarvam Document Intelligence (Sarvam Vision) for a PDF or an image.
126
+ See: https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/document-intelligence/overview
127
+ """
128
+ key = sarvam_api_key()
129
+ if not key:
130
+ return None, "SARVAM_API_KEY not configured", []
131
+ try:
132
+ from sarvamai import SarvamAI
133
+ except ImportError:
134
+ return None, "sarvamai package not installed (pip install sarvamai)", []
135
+
136
+ raw_bytes, suffix = _prepare_document_for_document_intel(file_bytes, mime)
137
+ tmp_file: str | None = None
138
+ tmp_zip: str | None = None
139
+ timeout = float(os.getenv("SARVAM_DOC_INTEL_TIMEOUT", "180"))
140
+ try:
141
+ fd, tmp_file = tempfile.mkstemp(suffix=suffix)
142
+ os.write(fd, raw_bytes)
143
+ os.close(fd)
144
+ client = SarvamAI(api_subscription_key=key, timeout=timeout)
145
+ lang = os.getenv("SARVAM_DOC_INTEL_LANGUAGE", "en-IN").strip()
146
+ job = client.document_intelligence.create_job(language=lang, output_format="md")
147
+ job.upload_file(tmp_file)
148
+ job.start()
149
+ status = job.wait_until_complete(timeout=timeout)
150
+ state = str(getattr(status, "job_state", "") or "")
151
+ if state not in ("Completed", "PartiallyCompleted"):
152
+ return None, f"Document intelligence job state: {state or 'unknown'}", []
153
+ zfd, tmp_zip = tempfile.mkstemp(suffix=".zip")
154
+ os.close(zfd)
155
+ job.download_output(tmp_zip)
156
+ text = _extract_markdown_from_output_zip(tmp_zip)
157
+ if not text:
158
+ return None, "empty document intelligence output", []
159
+ return text, None, _page_texts_from_output_zip(tmp_zip)
160
+ except Exception as e:
161
+ logger.warning("Sarvam document intelligence failed: %s", e)
162
+ return None, str(e), []
163
+ finally:
164
+ for tmp in (tmp_file, tmp_zip):
165
+ if tmp and os.path.isfile(tmp):
166
+ try:
167
+ os.unlink(tmp)
168
+ except OSError:
169
+ pass
170
+
171
+
172
+ def transcribe_handwritten_image(image_bytes: bytes, mime: str = "image/jpeg") -> tuple[str | None, str | None]:
173
+ """Sarvam Vision (Document Intelligence) → markdown/plain text from note images."""
174
+ return _document_intelligence(image_bytes, mime or "image/jpeg")
175
+
176
+
177
+ def transcribe_document_bytes(file_bytes: bytes, mime: str = "application/pdf") -> tuple[str | None, str | None]:
178
+ """Sarvam Vision (Document Intelligence) OCR for uploaded PDFs/images."""
179
+ return _document_intelligence(file_bytes, mime)
180
+
181
+
182
+ def transcribe_pdf_with_pages(file_bytes: bytes) -> tuple[str | None, str | None, list[str]]:
183
+ """Like transcribe_document_bytes for a PDF, plus each page's own text (when Sarvam provides it)."""
184
+ return _document_intelligence_with_pages(file_bytes, "application/pdf")
185
+
backend/onenote_sync.py CHANGED
@@ -1,4 +1,4 @@
1
- """Microsoft Graph OAuth + OneNote page sync into existing NoteScanner ingest pipeline."""
2
 
3
  from __future__ import annotations
4
 
@@ -12,10 +12,15 @@ from urllib.parse import urlencode
12
 
13
  import httpx
14
 
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"
@@ -216,9 +221,9 @@ def sync_onenote_pages_to_ingest(user_id: str, max_pages: int = 25) -> dict:
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:
 
1
+ """Microsoft Graph OAuth + OneNote page sync into existing Study AI ingest pipeline."""
2
 
3
  from __future__ import annotations
4
 
 
12
 
13
  import httpx
14
 
15
+ from backend.pipeline.indexing import index_note
16
+ from backend.store import (
17
+ onenote_token_get,
18
+ onenote_token_upsert,
19
+ user_document_upsert,
20
+ user_lock,
21
+ vfs_get_tree,
22
+ vfs_set_tree,
23
+ )
24
  from backend.vfs_tree import tree_add_folder, tree_add_file
25
 
26
  GRAPH_AUTHORIZE_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
 
221
  try:
222
  user_document_upsert(user_id, rel_path, text, source_title)
223
  except Exception:
224
+ # the stored text is used for viewing and study tools; the passages make it searchable.
225
  pass
226
+ index_note(user_id, rel_path, source_title, text)
227
  added.append((folder, file_name))
228
  ingested += 1
229
  except Exception as e:
backend/originals.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Students' original files (PDFs and photos) in an S3-compatible bucket (Neon Object Storage), so an
3
+ uploaded file opens on any device, not only the one it was uploaded from.
4
+
5
+ The text read from each file stays in Postgres (the documents table), which also records where the
6
+ file's original is (documents.original_key). The bucket is private: the website gets a link that
7
+ works for a few minutes. Keys are "<user id>/<random id><extension>", so moving or renaming a file
8
+ only changes its row, never the stored file.
9
+
10
+ Off when the bucket settings (AWS_ENDPOINT_URL_S3, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, S3_BUCKET)
11
+ aren't set: then only the text is kept. The course library's PDFs are not stored here (they stay in
12
+ Supabase).
13
+ """
14
+ import logging
15
+ import os
16
+ import threading
17
+ import uuid
18
+
19
+ from backend import db, settings
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ TYPES = {
24
+ ".pdf": "application/pdf",
25
+ ".jpg": "image/jpeg",
26
+ ".jpeg": "image/jpeg",
27
+ ".png": "image/png",
28
+ ".webp": "image/webp",
29
+ ".gif": "image/gif",
30
+ ".bmp": "image/bmp",
31
+ ".tiff": "image/tiff",
32
+ }
33
+ LINK_SECONDS = 600
34
+ MB = 1024 * 1024
35
+
36
+ # Tests plug in a fake S3 client here; None = boto3.
37
+ CLIENT = None
38
+ _client = None
39
+ _lock = threading.Lock()
40
+
41
+
42
+ def configured() -> bool:
43
+ return bool(
44
+ settings.FILES_S3_ENDPOINT
45
+ and settings.FILES_S3_BUCKET
46
+ and os.getenv("AWS_ACCESS_KEY_ID")
47
+ and os.getenv("AWS_SECRET_ACCESS_KEY")
48
+ )
49
+
50
+
51
+ def _s3():
52
+ global _client
53
+ if CLIENT is not None:
54
+ return CLIENT
55
+ with _lock:
56
+ if _client is None:
57
+ import boto3
58
+ from botocore.config import Config
59
+
60
+ _client = boto3.client(
61
+ "s3",
62
+ endpoint_url=settings.FILES_S3_ENDPOINT,
63
+ region_name=settings.FILES_S3_REGION,
64
+ config=Config(signature_version="s3v4", s3={"addressing_style": "path"}, retries={"max_attempts": 3}),
65
+ )
66
+ return _client
67
+
68
+
69
+ def _stored_mb(user_id: str | None = None) -> float:
70
+ if user_id is None:
71
+ total = db.scalar("SELECT coalesce(sum(original_size), 0) FROM documents")
72
+ else:
73
+ total = db.scalar("SELECT coalesce(sum(original_size), 0) FROM documents WHERE user_id = :u", u=user_id)
74
+ return int(total or 0) / MB
75
+
76
+
77
+ def keep(user_id: str, path: str, name: str, data: bytes) -> str:
78
+ """
79
+ Store the original of an uploaded file whose text is already saved at `path`.
80
+ Returns "" when it was kept (or isn't a PDF/photo), else a short note for the student.
81
+ """
82
+ content_type = TYPES.get(os.path.splitext(name)[1].lower())
83
+ if not content_type or not data or not configured():
84
+ return ""
85
+ size_mb = len(data) / MB
86
+ if _stored_mb(user_id) + size_mb > settings.MAX_STORED_FILES_MB_PER_USER:
87
+ return "The original file wasn't kept: your file storage is full (the text is saved)."
88
+ if _stored_mb() + size_mb > settings.MAX_STORED_FILES_MB_TOTAL:
89
+ logger.warning("File storage is full (MAX_STORED_FILES_MB_TOTAL)")
90
+ return "The original file wasn't kept: file storage is full right now (the text is saved)."
91
+ key = f"{user_id}/{uuid.uuid4().hex}{os.path.splitext(name)[1].lower()}"
92
+ try:
93
+ _s3().put_object(Bucket=settings.FILES_S3_BUCKET, Key=key, Body=data, ContentType=content_type)
94
+ except Exception:
95
+ logger.exception("Couldn't store the original of %s", path)
96
+ return "The original file couldn't be kept (the text is saved)."
97
+ with db.transaction() as conn:
98
+ old = db.scalar(
99
+ "SELECT original_key FROM documents WHERE user_id = :u AND path = :p FOR UPDATE", conn, u=user_id, p=path
100
+ )
101
+ changed = db.execute(
102
+ "UPDATE documents SET original_key = :k, original_type = :t, original_size = :n "
103
+ "WHERE user_id = :u AND path = :p",
104
+ conn,
105
+ u=user_id,
106
+ p=path,
107
+ k=key,
108
+ t=content_type,
109
+ n=len(data),
110
+ )
111
+ remove([old] if changed else [key]) # the replaced original, or the new one if its file is gone
112
+ return ""
113
+
114
+
115
+ def link(user_id: str, path: str) -> dict | None:
116
+ """A short-lived link to the original of a file: {"url", "name", "type"}, or None if there isn't one."""
117
+ if not configured():
118
+ return None
119
+ row = db.one(
120
+ "SELECT original_key, original_type, original_filename FROM documents "
121
+ "WHERE user_id = :u AND path = :p AND original_key <> ''",
122
+ u=user_id,
123
+ p=path,
124
+ )
125
+ if not row:
126
+ return None
127
+ name = row["original_filename"] or os.path.basename(path)
128
+ safe = "".join(c if c.isascii() and c not in '"\\' and c.isprintable() else "_" for c in name)
129
+ url = _s3().generate_presigned_url(
130
+ "get_object",
131
+ Params={
132
+ "Bucket": settings.FILES_S3_BUCKET,
133
+ "Key": row["original_key"],
134
+ "ResponseContentType": row["original_type"],
135
+ "ResponseContentDisposition": f'inline; filename="{safe}"',
136
+ },
137
+ ExpiresIn=LINK_SECONDS,
138
+ )
139
+ return {"url": url, "name": name, "type": row["original_type"]}
140
+
141
+
142
+ def remove(keys: list[str]) -> None:
143
+ """Delete stored originals (best effort: a leftover file only costs storage)."""
144
+ keys = [k for k in keys if k]
145
+ if not keys or not configured():
146
+ return
147
+ for i in range(0, len(keys), 1000):
148
+ batch = keys[i : i + 1000]
149
+ try:
150
+ _s3().delete_objects(
151
+ Bucket=settings.FILES_S3_BUCKET, Delete={"Objects": [{"Key": k} for k in batch], "Quiet": True}
152
+ )
153
+ except Exception:
154
+ logger.exception("Couldn't delete %d stored originals", len(batch))
155
+
156
+
157
+ def remove_user(user_id: str) -> None:
158
+ """Delete every stored original of a user (account deletion)."""
159
+ if not configured() or not user_id:
160
+ return
161
+ keys: list[str] = []
162
+ token = None
163
+ while True:
164
+ kwargs = {"Bucket": settings.FILES_S3_BUCKET, "Prefix": f"{user_id}/"}
165
+ if token:
166
+ kwargs["ContinuationToken"] = token
167
+ page = _s3().list_objects_v2(**kwargs)
168
+ keys += [o["Key"] for o in page.get("Contents", [])]
169
+ if not page.get("IsTruncated"):
170
+ break
171
+ token = page.get("NextContinuationToken")
172
+ remove(keys)
backend/paths.py CHANGED
@@ -1,8 +1,7 @@
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
 
@@ -75,7 +74,6 @@ def get_vfs_tree_clean(user_id: str) -> list:
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
 
 
1
  """Virtual-path cleanup and folder-tree reads shared by the routes."""
2
  import copy
3
 
4
+ from backend.store import user_lock, vfs_get_tree, vfs_set_tree
 
5
  from backend.vfs_tree import flatten_file_paths
6
 
7
 
 
74
  with user_lock(user_id):
75
  fixed = _normalize_vfs_tree(vfs_get_tree(user_id))
76
  vfs_set_tree(user_id, fixed)
 
77
  return fixed
78
 
79
 
backend/pipeline/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The notes pipeline, built on LlamaIndex with Postgres (pgvector) as its store:
3
+
4
+ models.py the search model, the re-checking model and the language model
5
+ indexing.py text → passages → meaning fingerprints → Postgres (with a keyword index)
6
+ retrieval.py question → keyword + meaning search in each place → re-check → best passages
7
+ generation.py passages + question → answer (or flashcards, quizzes, summaries)
8
+
9
+ Reading text out of PDFs and photos happens before this, in backend/ocr.py.
10
+ """
backend/{llm_pipeline.py → pipeline/generation.py} RENAMED
@@ -1,24 +1,30 @@
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-105b" # Sarvam retired sarvam-30b in 2026
19
- # Flashcards, quizzes and summaries don't need the model's long reasoning: without it they take
20
- # about a second instead of up to a minute, and cost a fraction of the tokens.
21
- _STUDY_REASONING_EFFORT = "off"
22
 
23
  _GROUNDING_STOPWORDS = {
24
  "about", "after", "again", "also", "among", "another", "because", "before", "being", "between",
@@ -28,6 +34,11 @@ _GROUNDING_STOPWORDS = {
28
  }
29
 
30
 
 
 
 
 
 
31
  _usage = threading.local()
32
 
33
 
@@ -42,7 +53,7 @@ def estimate_tokens(text: str) -> int:
42
 
43
 
44
  def take_usage() -> dict:
45
- """AI tokens used by chat calls made in this thread since the last call (then resets to zero)."""
46
  out = {"prompt_tokens": getattr(_usage, "prompt", 0), "completion_tokens": getattr(_usage, "completion", 0)}
47
  _usage.prompt = _usage.completion = 0
48
  return out
@@ -57,337 +68,192 @@ def language_instruction(language: str | None) -> str:
57
  )
58
 
59
 
60
- def _sarvam_api_key() -> str | None:
61
- k = os.getenv("SARVAM_API_KEY")
62
- return k.strip() if k else None
63
 
64
 
65
- def _chat_base_url() -> str:
66
- return os.getenv("SARVAM_API_BASE", "https://api.sarvam.ai").rstrip("/")
67
 
68
 
69
- def _model_rag() -> str:
70
- return (os.getenv("SARVAM_MODEL_RAG") or "").strip() or _DEFAULT_MODEL_RAG
 
 
 
 
 
71
 
72
 
73
- def _model_study() -> str:
74
- return (os.getenv("SARVAM_MODEL_STUDY") or "").strip() or _DEFAULT_MODEL_STUDY
 
 
 
 
75
 
76
 
77
- def _sarvam_chat_complete(
78
  messages: list[dict[str, str]],
79
- *,
80
- model: str,
81
  max_tokens: int,
82
  temperature: float,
83
- reasoning_effort: str | None = None,
84
  ) -> tuple[str | None, str | None]:
85
- key = _sarvam_api_key()
86
- if not key:
87
- return None, "SARVAM_API_KEY not configured"
88
- url = f"{_chat_base_url()}/v1/chat/completions"
89
- payload = {"model": model, "messages": messages, "max_tokens": max_tokens, "temperature": temperature}
90
- if reasoning_effort == "off":
91
- payload["reasoning_effort"] = None # Sarvam: an explicit null turns reasoning off
92
- elif reasoning_effort:
93
- payload["reasoning_effort"] = reasoning_effort # low | medium (default) | high | max
94
- try:
95
- r = httpx.post(
96
- url,
97
- headers={
98
- "Authorization": f"Bearer {key}",
99
- "Content-Type": "application/json",
100
- },
101
- json=payload,
102
- timeout=300.0,
103
- )
104
- data = r.json()
105
- if r.status_code >= 400:
106
- err = data.get("error") if isinstance(data.get("error"), dict) else {}
107
- msg = err.get("message") if isinstance(err, dict) else None
108
- if "deprecated" in (msg or "").lower() and model != _DEFAULT_MODEL_RAG:
109
- # A model setting that Sarvam has since retired: keep working on the default model.
110
- logger.warning("Sarvam model %s is retired (%s); using %s", model, msg, _DEFAULT_MODEL_RAG)
111
- return _sarvam_chat_complete(
112
- messages,
113
- model=_DEFAULT_MODEL_RAG,
114
- max_tokens=max_tokens,
115
- temperature=temperature,
116
- reasoning_effort=reasoning_effort,
117
- )
118
- return None, msg or r.text or f"HTTP {r.status_code}"
119
- choices = data.get("choices") or []
120
- if not choices:
121
- return None, "no choices in response"
122
- content = (choices[0].get("message") or {}).get("content")
123
- usage = data.get("usage") if isinstance(data.get("usage"), dict) else {}
124
  _add_usage(
125
- usage.get("prompt_tokens") or estimate_tokens(json.dumps(messages)),
126
- usage.get("completion_tokens") or estimate_tokens(str(content or "")),
127
  )
128
- if content is None or not str(content).strip():
129
- return None, "empty model content"
130
- return str(content).strip(), None
131
- except httpx.RequestError as e:
132
- return None, str(e)
133
- except Exception as e:
134
- return None, str(e)
135
-
136
-
137
- def _prepare_image_for_document_intel(image_bytes: bytes, mime: str) -> tuple[bytes, str]:
138
- """Document Intelligence accepts PNG/JPEG/PDF; normalize webp/gif to JPEG."""
139
- m = (mime or "image/jpeg").lower()
140
- if m in ("image/webp", "image/gif"):
141
- from io import BytesIO
142
-
143
- from PIL import Image
144
-
145
- im = Image.open(BytesIO(image_bytes)).convert("RGB")
146
- out = BytesIO()
147
- im.save(out, format="JPEG", quality=92)
148
- return out.getvalue(), ".jpg"
149
- if m == "image/png":
150
- return image_bytes, ".png"
151
- return image_bytes, ".jpg"
152
-
153
-
154
- def _prepare_document_for_document_intel(file_bytes: bytes, mime: str) -> tuple[bytes, str]:
155
- """Normalize uploads for Sarvam Document Intelligence (image or PDF)."""
156
- m = (mime or "").lower().strip()
157
- if m == "application/pdf":
158
- return file_bytes, ".pdf"
159
- return _prepare_image_for_document_intel(file_bytes, m or "image/jpeg")
160
-
161
-
162
- # Sarvam's markdown embeds every figure it finds as a base64 image: often hundreds of KB per page,
163
- # which would flood search with junk passages. Keep a short marker instead.
164
- _INLINE_IMAGE_RES = (
165
- re.compile(r"!\[[^\]]*\]\(\s*data:[^)]*\)"),
166
- re.compile(r"<img\b[^>]*\bsrc\s*=\s*[\"']data:[^\"']*[\"'][^>]*>", re.IGNORECASE),
167
- re.compile(r"data:image/[\w.+-]+;base64,[A-Za-z0-9+/=\s]{64,}"),
168
  )
169
 
170
 
171
- def strip_inline_images(text: str) -> str:
172
- for pattern in _INLINE_IMAGE_RES:
173
- text = pattern.sub("[figure]", text or "")
174
- return text
175
-
176
-
177
- def _extract_markdown_from_output_zip(zip_path: str) -> str:
178
- with zipfile.ZipFile(zip_path, "r") as z:
179
- names = sorted(z.namelist())
180
- md_names = [n for n in names if n.lower().endswith(".md")]
181
- html_names = [n for n in names if n.lower().endswith((".html", ".htm"))]
182
- pick = (md_names[0] if md_names else None) or (html_names[0] if html_names else None) or (
183
- names[0] if names else None
184
- )
185
- if not pick:
186
- return ""
187
- return strip_inline_images(z.read(pick).decode("utf-8", errors="replace")).strip()
188
-
189
-
190
- def _strings_in(value) -> list[str]:
191
- if isinstance(value, str):
192
- return [value]
193
- if isinstance(value, dict):
194
- out = []
195
- for k in ("text", "content", "markdown"):
196
- if isinstance(value.get(k), str):
197
- out.append(value[k])
198
- for v in value.values():
199
- if isinstance(v, (dict, list)):
200
- out.extend(_strings_in(v))
201
- return out
202
- if isinstance(value, list):
203
- return [s for v in value for s in _strings_in(v)]
204
- return []
205
-
206
-
207
- def _page_texts_from_output_zip(zip_path: str) -> list[str]:
208
- """Per-page text from metadata/page_NNN.json files in a Document Intelligence output zip ([] if absent)."""
209
- pages: list[tuple[int, str]] = []
210
- try:
211
- with zipfile.ZipFile(zip_path, "r") as z:
212
- for name in z.namelist():
213
- m = re.search(r"page_(\d+)\.json$", name)
214
- if not m:
215
- continue
216
- try:
217
- data = json.loads(z.read(name).decode("utf-8", errors="replace"))
218
- except json.JSONDecodeError:
219
- continue
220
- pages.append((int(m.group(1)), strip_inline_images(" ".join(_strings_in(data)))))
221
- except zipfile.BadZipFile:
222
- return []
223
- return [text for _, text in sorted(pages)]
224
-
225
-
226
- def _document_intelligence(file_bytes: bytes, mime: str) -> tuple[str | None, str | None]:
227
- text, err, _pages = _document_intelligence_with_pages(file_bytes, mime)
228
- return text, err
229
-
230
-
231
- def _document_intelligence_with_pages(file_bytes: bytes, mime: str) -> tuple[str | None, str | None, list[str]]:
232
  """
233
- OCR / layout text via Sarvam Document Intelligence (Sarvam Vision) for a PDF or an image.
234
- See: https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/document-intelligence/overview
235
  """
236
- key = _sarvam_api_key()
237
- if not key:
238
- return None, "SARVAM_API_KEY not configured", []
239
- try:
240
- from sarvamai import SarvamAI
241
- except ImportError:
242
- return None, "sarvamai package not installed (pip install sarvamai)", []
243
-
244
- raw_bytes, suffix = _prepare_document_for_document_intel(file_bytes, mime)
245
- tmp_file: str | None = None
246
- tmp_zip: str | None = None
247
- timeout = float(os.getenv("SARVAM_DOC_INTEL_TIMEOUT", "180"))
248
- try:
249
- fd, tmp_file = tempfile.mkstemp(suffix=suffix)
250
- os.write(fd, raw_bytes)
251
- os.close(fd)
252
- client = SarvamAI(api_subscription_key=key, timeout=timeout)
253
- lang = os.getenv("SARVAM_DOC_INTEL_LANGUAGE", "en-IN").strip()
254
- job = client.document_intelligence.create_job(language=lang, output_format="md")
255
- job.upload_file(tmp_file)
256
- job.start()
257
- status = job.wait_until_complete(timeout=timeout)
258
- state = str(getattr(status, "job_state", "") or "")
259
- if state not in ("Completed", "PartiallyCompleted"):
260
- return None, f"Document intelligence job state: {state or 'unknown'}", []
261
- zfd, tmp_zip = tempfile.mkstemp(suffix=".zip")
262
- os.close(zfd)
263
- job.download_output(tmp_zip)
264
- text = _extract_markdown_from_output_zip(tmp_zip)
265
- if not text:
266
- return None, "empty document intelligence output", []
267
- return text, None, _page_texts_from_output_zip(tmp_zip)
268
- except Exception as e:
269
- logger.warning("Sarvam document intelligence failed: %s", e)
270
- return None, str(e), []
271
- finally:
272
- for tmp in (tmp_file, tmp_zip):
273
- if tmp and os.path.isfile(tmp):
274
- try:
275
- os.unlink(tmp)
276
- except OSError:
277
- pass
278
 
279
 
280
- def transcribe_handwritten_image(image_bytes: bytes, mime: str = "image/jpeg") -> tuple[str | None, str | None]:
281
- """Sarvam Vision (Document Intelligence) → markdown/plain text from note images."""
282
- return _document_intelligence(image_bytes, mime or "image/jpeg")
283
 
284
 
285
- def transcribe_document_bytes(file_bytes: bytes, mime: str = "application/pdf") -> tuple[str | None, str | None]:
286
- """Sarvam Vision (Document Intelligence) OCR for uploaded PDFs/images."""
287
- return _document_intelligence(file_bytes, mime)
 
 
 
 
 
 
288
 
289
 
290
- def transcribe_pdf_with_pages(file_bytes: bytes) -> tuple[str | None, str | None, list[str]]:
291
- """Like transcribe_document_bytes for a PDF, plus each page's own text (when Sarvam provides it)."""
292
- return _document_intelligence_with_pages(file_bytes, "application/pdf")
 
 
 
 
 
 
 
 
 
 
 
 
293
 
294
 
295
- def _rag_messages(question: str, context: str, language: str = "English") -> list[dict[str, str]]:
296
- ctx = (context or "").strip()[:60000]
297
- q = (question or "").strip()
298
- lang = language_instruction(language)
299
- messages = [
300
- {
301
- "role": "system",
302
- "content": (
303
- "You are a brilliant subject-matter tutor helping a student prepare for exams.\n\n"
304
- "GROUNDING RULES:\n"
305
- "- The student's notes are your PRIMARY source of truth.\n"
306
- "- Identify the subject/topic from the notes (e.g. Machine Learning, Linear Algebra, Operating Systems).\n"
307
- "- ALWAYS answer the student's question — never refuse or say 'not in notes'.\n"
308
- "- When the notes contain the answer, cite specific details from them.\n"
309
- "- Excerpts marked (main source) come from files the student marked as most reliable; prefer them.\n"
310
- "- When the notes are incomplete, supplement with correct, textbook-level knowledge for THAT subject.\n"
311
- " Mark such additions with '📖 Beyond notes:' so the student knows.\n"
312
- "- NEVER drift to unrelated subjects. If asked about something outside the course scope, "
313
- " briefly redirect: 'That's outside [subject]. Here's what your notes cover instead…'\n\n"
314
- "TEACHING STYLE:\n"
315
- "- Explain like a great tutor: clear, concise, with examples.\n"
316
- "- For problem-solving: show step-by-step working.\n"
317
- "- For tricky exam practice: generate 5-8 challenging questions with concise answer keys.\n"
318
- "- Use Markdown: bullet points, short paragraphs, tables when useful.\n"
319
- "- Write math in LaTeX: $...$ inline and $$...$$ for display equations.\n"
320
- "- Do not claim inability to access files or notes."
321
- ),
322
- },
323
- {
324
- "role": "user",
325
- "content": (
326
- f"**Student's question:** {q}\n\n"
327
- f"**Notes excerpts:**\n{ctx}\n\n"
328
- "Answer the question fully. Use notes evidence first, then subject knowledge if needed."
329
- ),
330
- },
331
- ]
332
- if lang:
333
- messages[0]["content"] += "\n- " + lang
334
- return messages
335
 
336
 
337
- def sarvam_rag_answer(question: str, context: str, language: str = "English") -> tuple[str | None, str | None]:
338
- """Answer from notes-first context with constrained subject verification."""
339
- if not (question or "").strip():
340
- return None, "Empty query"
341
- return _sarvam_chat_complete(
342
- _rag_messages(question, context, language),
343
- model=_model_rag(),
344
- max_tokens=4096,
345
- temperature=0.3,
346
  )
 
 
 
 
 
 
 
 
 
 
 
 
347
 
348
 
349
- class LLMError(Exception):
350
- """The AI service failed; the message is safe to log, not meant for students."""
351
-
352
-
353
- def sarvam_rag_answer_stream(question: str, context: str, language: str = "English") -> Iterator[str]:
354
- """
355
- Same answer as sarvam_rag_answer, yielded piece by piece as the model writes it
356
- (server-sent events, `stream: true`). Raises LLMError if the request fails.
357
- """
358
- key = _sarvam_api_key()
359
- if not key:
360
- raise LLMError("SARVAM_API_KEY not configured")
361
- url = f"{_chat_base_url()}/v1/chat/completions"
362
- payload = {
363
- "model": _model_rag(),
364
- "messages": _rag_messages(question, context, language),
365
- "max_tokens": 4096,
366
- "temperature": 0.3,
367
- "stream": True,
368
- }
369
- headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
370
- try:
371
- with httpx.stream("POST", url, headers=headers, json=payload, timeout=300.0) as r:
372
- if r.status_code >= 400:
373
- r.read()
374
- raise LLMError(f"HTTP {r.status_code}: {r.text[:300]}")
375
- for line in r.iter_lines():
376
- if not line or not line.startswith("data:"):
377
- continue
378
- data = line[5:].strip()
379
- if data == "[DONE]":
380
- break
381
- try:
382
- chunk = json.loads(data)
383
- except json.JSONDecodeError:
384
- continue
385
- for choice in chunk.get("choices") or []:
386
- piece = (choice.get("delta") or {}).get("content")
387
- if piece:
388
- yield piece
389
- except httpx.HTTPError as e:
390
- raise LLMError(str(e)) from e
391
 
392
 
393
  # Models often write LaTeX inside JSON strings with single backslashes: "\cdot" is an invalid JSON
@@ -410,12 +276,9 @@ def _parse_json_loose(raw: str) -> Any:
410
 
411
 
412
  def _tokens(text: str) -> list[str]:
413
- # 3+ chars: math/CS terms like "ref", "rref", "row"
414
- return [
415
- t
416
- for t in re.findall(r"[a-zA-Z][a-zA-Z0-9]{2,}", (text or "").lower())
417
- if t not in _GROUNDING_STOPWORDS
418
- ]
419
 
420
 
421
  def _primary_body_from_study_ctx(ctx: str) -> str:
@@ -505,7 +368,7 @@ def _coerce_study_list(parsed: Any) -> list | None:
505
  return None
506
 
507
 
508
- def cheap_study_json(context: str, task: str, n: int, language: str = "English") -> tuple[Any, str | None]:
509
  ctx = context[:60000]
510
  body = _primary_body_from_study_ctx(ctx)
511
  keywords = _context_keywords(body or ctx)
@@ -552,13 +415,7 @@ def cheap_study_json(context: str, task: str, n: int, language: str = "English")
552
  last_err = "generation failed"
553
  for k in range(3):
554
  msg = prompt if k == 0 else (prompt + "\n\nPrevious output had formatting issues. Regenerate valid JSON strictly following the schema.")
555
- raw, err = _sarvam_chat_complete(
556
- [{"role": "user", "content": msg}],
557
- model=_model_study(),
558
- max_tokens=8192,
559
- temperature=0.4,
560
- reasoning_effort=_STUDY_REASONING_EFFORT,
561
- )
562
  if err:
563
  last_err = err
564
  continue
@@ -586,7 +443,7 @@ def cheap_study_json(context: str, task: str, n: int, language: str = "English")
586
  return None, f"The AI couldn't generate {label} right now. Please try again."
587
 
588
 
589
- def topic_summary(context: str, language: str = "English") -> tuple[str | None, str | None]:
590
  """Generate a concise 100-150 word summary covering all key topics from the notes."""
591
  ctx = (context or "").strip()[:60000]
592
  body = _primary_body_from_study_ctx(ctx)
@@ -611,13 +468,7 @@ def topic_summary(context: str, language: str = "English") -> tuple[str | None,
611
  last_err = "generation failed"
612
  for k in range(2):
613
  msg = prompt if k == 0 else (prompt + "\n\nPrevious output was too long or formatted incorrectly. Write 100-150 words of plain text only.")
614
- raw, err = _sarvam_chat_complete(
615
- [{"role": "user", "content": msg}],
616
- model=_model_study(),
617
- max_tokens=4096, # room for the model's reasoning as well as the ~150-word summary
618
- temperature=0.2,
619
- reasoning_effort=_STUDY_REASONING_EFFORT,
620
- )
621
  if err:
622
  last_err = err
623
  continue
 
1
+ """
2
+ Writing with the language model (the "generation" step of the pipeline), through LlamaIndex:
3
+
4
+ - answers to questions, from the passages retrieval.py found (whole or streamed word by word);
5
+ - rewriting a follow-up question ("explain that more simply") so it can be searched on its own;
6
+ - flashcards, multiple-choice quizzes and summaries for the study tools.
7
+
8
+ Answers use the notes first and label anything added from general knowledge "📖 Beyond notes".
9
+ The model is chosen in pipeline/models.py (Sarvam by default).
10
+ """
11
  import json
12
  import logging
 
13
  import random
14
  import re
 
15
  import threading
 
16
  from typing import Any, Iterator
17
 
18
+ from llama_index.core.llms import ChatMessage
19
+
20
+ from backend import settings
21
+ from backend.pipeline import models
22
+ from backend.settings import HISTORY_TURNS, LLM_PROVIDER
23
 
24
  logger = logging.getLogger(__name__)
25
 
26
+ ANSWER_MAX_TOKENS = 4096
27
+ HISTORY_CHARS = 1500 # of each earlier message (answers can be long; the gist is enough)
 
 
 
 
28
 
29
  _GROUNDING_STOPWORDS = {
30
  "about", "after", "again", "also", "among", "another", "because", "before", "being", "between",
 
34
  }
35
 
36
 
37
+ class GenerationError(Exception):
38
+ """The language model failed; the message is safe to log, not meant for students."""
39
+
40
+
41
+ # ---------- Token counting (for the cost figures on the admin page) ----------
42
  _usage = threading.local()
43
 
44
 
 
53
 
54
 
55
  def take_usage() -> dict:
56
+ """AI tokens used by calls made in this thread since the last call (then resets to zero)."""
57
  out = {"prompt_tokens": getattr(_usage, "prompt", 0), "completion_tokens": getattr(_usage, "completion", 0)}
58
  _usage.prompt = _usage.completion = 0
59
  return out
 
68
  )
69
 
70
 
71
+ # ---------- Calling the model ----------
72
+ _NOT_CONFIGURED = "The language model isn't configured (SARVAM_API_KEY, or LLM_API_BASE and LLM_MODEL)."
 
73
 
74
 
75
+ def _messages(raw: list[dict[str, str]]) -> list[ChatMessage]:
76
+ return [ChatMessage(role=m["role"], content=m["content"]) for m in raw]
77
 
78
 
79
+ def _retired(error: Exception, model: str | None) -> bool:
80
+ """A model setting that Sarvam has since retired (keep working on the default model)."""
81
+ return (
82
+ LLM_PROVIDER == "sarvam"
83
+ and "deprecated" in str(error).lower()
84
+ and (model or "") != models.SARVAM_DEFAULT_MODEL
85
+ )
86
 
87
 
88
+ def _reported_usage(raw) -> tuple[int, int]:
89
+ """(prompt, completion) tokens the API reported for a reply, 0 when it didn't."""
90
+ used = raw.get("usage") if isinstance(raw, dict) else getattr(raw, "usage", None)
91
+ if isinstance(used, dict):
92
+ return int(used.get("prompt_tokens") or 0), int(used.get("completion_tokens") or 0)
93
+ return int(getattr(used, "prompt_tokens", 0) or 0), int(getattr(used, "completion_tokens", 0) or 0)
94
 
95
 
96
+ def chat(
97
  messages: list[dict[str, str]],
98
+ purpose: str,
 
99
  max_tokens: int,
100
  temperature: float,
101
+ reasoning: str | None = None,
102
  ) -> tuple[str | None, str | None]:
103
+ """One reply from the language model: (text, None) or (None, error message)."""
104
+ if not models.llm_configured():
105
+ return None, _NOT_CONFIGURED
106
+ model = None
107
+ for _attempt in range(2):
108
+ llm = models.llm(purpose, max_tokens, temperature, reasoning, model)
109
+ try:
110
+ reply = llm.chat(_messages(messages))
111
+ except Exception as e:
112
+ if _retired(e, llm.model):
113
+ logger.warning("Model %s is retired (%s); using %s", llm.model, e, models.SARVAM_DEFAULT_MODEL)
114
+ model = models.SARVAM_DEFAULT_MODEL
115
+ continue
116
+ return None, str(e)
117
+ content = (reply.message.content or "").strip()
118
+ prompt_tokens, completion_tokens = _reported_usage(reply.raw)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  _add_usage(
120
+ prompt_tokens or estimate_tokens(json.dumps(messages)),
121
+ completion_tokens or estimate_tokens(content),
122
  )
123
+ return (content, None) if content else (None, "empty model content")
124
+ return None, "model retired"
125
+
126
+
127
+ # ---------- Answers ----------
128
+ SYSTEM_PROMPT = (
129
+ "You are a brilliant subject-matter tutor helping a student prepare for exams.\n\n"
130
+ "GROUNDING RULES:\n"
131
+ "- The student's notes are your PRIMARY source of truth.\n"
132
+ "- Identify the subject/topic from the notes (e.g. Machine Learning, Linear Algebra, Operating Systems).\n"
133
+ "- ALWAYS answer the student's question — never refuse or say 'not in notes'.\n"
134
+ "- When the notes contain the answer, cite specific details from them.\n"
135
+ "- Excerpts marked (main source) come from files the student marked as most reliable; prefer them.\n"
136
+ "- When the notes are incomplete, supplement with correct, textbook-level knowledge for THAT subject.\n"
137
+ " Mark such additions with '📖 Beyond notes:' so the student knows.\n"
138
+ "- NEVER drift to unrelated subjects. If asked about something outside the course scope, "
139
+ " briefly redirect: 'That's outside [subject]. Here's what your notes cover instead…'\n\n"
140
+ "TEACHING STYLE:\n"
141
+ "- Explain like a great tutor: clear, concise, with examples.\n"
142
+ "- For problem-solving: show step-by-step working.\n"
143
+ "- For tricky exam practice: generate 5-8 challenging questions with concise answer keys.\n"
144
+ "- Use Markdown: bullet points, short paragraphs, tables when useful.\n"
145
+ "- Write math in LaTeX: $...$ inline and $$...$$ for display equations.\n"
146
+ "- Do not claim inability to access files or notes.\n"
147
+ "- Earlier messages of the conversation are given for context; the notes excerpts belong to the latest question."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  )
149
 
150
 
151
+ def clean_history(history: list[dict] | None) -> list[dict[str, str]]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  """
153
+ The last HISTORY_TURNS messages as alternating user/assistant turns, starting with the student
154
+ and ending with an answer (the new question follows). Long messages are shortened.
155
  """
156
+ turns: list[dict[str, str]] = []
157
+ for m in (history or [])[-HISTORY_TURNS * 2:]:
158
+ if not isinstance(m, dict):
159
+ continue
160
+ role = "assistant" if m.get("role") in ("assistant", "ai", "bot") else "user"
161
+ content = str(m.get("content") or m.get("text") or "").strip()[:HISTORY_CHARS]
162
+ if not content:
163
+ continue
164
+ if turns and turns[-1]["role"] == role:
165
+ turns[-1]["content"] += "\n\n" + content
166
+ else:
167
+ turns.append({"role": role, "content": content})
168
+ while turns and turns[0]["role"] != "user":
169
+ turns.pop(0)
170
+ while turns and turns[-1]["role"] != "assistant":
171
+ turns.pop()
172
+ return turns[-HISTORY_TURNS:]
173
+
174
+
175
+ def answer_messages(
176
+ question: str, context: str, language: str = "English", history: list[dict] | None = None
177
+ ) -> list[dict[str, str]]:
178
+ lang = language_instruction(language)
179
+ system = SYSTEM_PROMPT + ("\n- " + lang if lang else "")
180
+ final = {
181
+ "role": "user",
182
+ "content": (
183
+ f"**Student's question:** {(question or '').strip()}\n\n"
184
+ f"**Notes excerpts:**\n{(context or '').strip()[:60000]}\n\n"
185
+ "Answer the question fully. Use notes evidence first, then subject knowledge if needed."
186
+ ),
187
+ }
188
+ return [{"role": "system", "content": system}, *clean_history(history), final]
 
 
 
 
 
 
 
 
 
189
 
190
 
191
+ def _answer_reasoning() -> str | None:
192
+ return None if settings.ANSWER_THINKING else "off"
 
193
 
194
 
195
+ def answer(
196
+ question: str, context: str, language: str = "English", history: list[dict] | None = None
197
+ ) -> tuple[str | None, str | None]:
198
+ """The whole answer at once: (text, None) or (None, error)."""
199
+ if not (question or "").strip():
200
+ return None, "Empty query"
201
+ return chat(
202
+ answer_messages(question, context, language, history), "answer", ANSWER_MAX_TOKENS, 0.3, _answer_reasoning()
203
+ )
204
 
205
 
206
+ def answer_stream(
207
+ question: str, context: str, language: str = "English", history: list[dict] | None = None
208
+ ) -> Iterator[str]:
209
+ """The answer piece by piece as the model writes it. Raises GenerationError if the request fails."""
210
+ if not models.llm_configured():
211
+ raise GenerationError(_NOT_CONFIGURED)
212
+ llm = models.llm("answer", ANSWER_MAX_TOKENS, 0.3, _answer_reasoning())
213
+ try:
214
+ for chunk in llm.stream_chat(_messages(answer_messages(question, context, language, history))):
215
+ if chunk.delta:
216
+ yield chunk.delta
217
+ except GenerationError:
218
+ raise
219
+ except Exception as e:
220
+ raise GenerationError(str(e)) from e
221
 
222
 
223
+ # ---------- Follow-up questions ----------
224
+ CONDENSE_PROMPT = (
225
+ "Rewrite the student's latest message as one question that can be understood without the "
226
+ "conversation, so it can be searched for in their notes: replace words like 'it', 'that' or "
227
+ "'the second one' with what they refer to. Keep the student's language and wording. If the "
228
+ "message already stands on its own, return it unchanged. Reply with the question only.\n\n"
229
+ "Conversation:\n{conversation}\n\nLatest message: {question}"
230
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
 
232
 
233
+ def standalone_question(question: str, history: list[dict] | None) -> str:
234
+ """The question rewritten to stand on its own (unchanged when there is no earlier conversation)."""
235
+ turns = clean_history(history)
236
+ if not turns or not (question or "").strip():
237
+ return question
238
+ conversation = "\n".join(
239
+ f"{'Student' if t['role'] == 'user' else 'Tutor'}: {t['content'][:600]}" for t in turns
 
 
240
  )
241
+ text, err = chat(
242
+ [{"role": "user", "content": CONDENSE_PROMPT.format(conversation=conversation, question=question.strip())}],
243
+ "study",
244
+ max_tokens=300,
245
+ temperature=0.0,
246
+ reasoning="off",
247
+ )
248
+ if err or not text:
249
+ logger.info("Couldn't rewrite a follow-up question (%s); searching with it as asked", err)
250
+ return question
251
+ text = text.strip().strip('"').strip()
252
+ return text if 0 < len(text) <= 1000 else question
253
 
254
 
255
+ # ---------- Study tools ----------
256
+ _STUDY_REASONING = "off" # flashcards, quizzes and summaries don't need the model's long reasoning
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
 
259
  # Models often write LaTeX inside JSON strings with single backslashes: "\cdot" is an invalid JSON
 
276
 
277
 
278
  def _tokens(text: str) -> list[str]:
279
+ """Words of 3+ characters in any script (math/CS terms like "ref", "rref"; Hindi words too)."""
280
+ words = (w.strip(".,;:!?()[]{}<>\"'`*_#|-–—«»“”‘’।") for w in (text or "").lower().split())
281
+ return [w for w in words if len(w) >= 3 and not w.isdigit() and w not in _GROUNDING_STOPWORDS]
 
 
 
282
 
283
 
284
  def _primary_body_from_study_ctx(ctx: str) -> str:
 
368
  return None
369
 
370
 
371
+ def study_items(context: str, task: str, n: int, language: str = "English") -> tuple[Any, str | None]:
372
  ctx = context[:60000]
373
  body = _primary_body_from_study_ctx(ctx)
374
  keywords = _context_keywords(body or ctx)
 
415
  last_err = "generation failed"
416
  for k in range(3):
417
  msg = prompt if k == 0 else (prompt + "\n\nPrevious output had formatting issues. Regenerate valid JSON strictly following the schema.")
418
+ raw, err = chat([{"role": "user", "content": msg}], "study", 8192, 0.4, _STUDY_REASONING)
 
 
 
 
 
 
419
  if err:
420
  last_err = err
421
  continue
 
443
  return None, f"The AI couldn't generate {label} right now. Please try again."
444
 
445
 
446
+ def summary(context: str, language: str = "English") -> tuple[str | None, str | None]:
447
  """Generate a concise 100-150 word summary covering all key topics from the notes."""
448
  ctx = (context or "").strip()[:60000]
449
  body = _primary_body_from_study_ctx(ctx)
 
468
  last_err = "generation failed"
469
  for k in range(2):
470
  msg = prompt if k == 0 else (prompt + "\n\nPrevious output was too long or formatted incorrectly. Write 100-150 words of plain text only.")
471
+ raw, err = chat([{"role": "user", "content": msg}], "study", 4096, 0.2, _STUDY_REASONING)
 
 
 
 
 
 
472
  if err:
473
  last_err = err
474
  continue
backend/pipeline/indexing.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Saving text for search: cut it into passages, make a meaning fingerprint for each passage, and store
3
+ both in Postgres through LlamaIndex's vector store. The same rows also get a keyword index, so search
4
+ can match exact words ("RREF", "Dijkstra") as well as meaning.
5
+
6
+ Two passage tables (LlamaIndex adds the data_ prefix):
7
+ - data_notes every student's own notes; every read and search is limited to one user_id
8
+ - data_library the shared course library (library.py): one copy, searched by every student
9
+
10
+ Safety: LlamaIndex writes metadata filter values straight into its SQL, so filters only ever use
11
+ values the server made itself: user ids (checked) and hashed keys of paths, courses and subjects
12
+ (path_key, course_key, subject_key). SQL written here always uses bound parameters.
13
+ """
14
+ import hashlib
15
+ import logging
16
+ import re
17
+ import threading
18
+ import uuid
19
+
20
+ from llama_index.core import Document
21
+ from llama_index.core.node_parser import SentenceSplitter
22
+ from llama_index.core.schema import TextNode
23
+ from llama_index.core.vector_stores.types import FilterOperator, MetadataFilter, MetadataFilters
24
+
25
+ from backend import db, settings
26
+ from backend.pages import PageStarts, page_at
27
+ from backend.pipeline import models
28
+ from backend.store import clean_text
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ NOTES_TABLE = "notes" # → data_notes
33
+ LIBRARY_TABLE = "library" # → data_library
34
+ EMBED_BATCH = 64
35
+ _SAFE_ID = re.compile(r"^[A-Za-z0-9_-]{1,80}$")
36
+
37
+ _stores: dict[str, object] = {}
38
+ _stores_lock = threading.Lock()
39
+
40
+
41
+ # ---------- Keys used in filters ----------
42
+ def key(kind: str, value: str) -> str:
43
+ """Filter-safe key for a path, course or subject: a letter and 40 hex digits."""
44
+ return kind[0] + hashlib.sha256((value or "").encode("utf-8")).hexdigest()[:40]
45
+
46
+
47
+ def path_key(path: str) -> str:
48
+ return key("p", path)
49
+
50
+
51
+ def course_key(course: str) -> str:
52
+ return key("c", course)
53
+
54
+
55
+ def subject_key(subject: str) -> str:
56
+ return key("s", subject)
57
+
58
+
59
+ def safe_user_id(user_id: str) -> str:
60
+ if not _SAFE_ID.match(user_id or ""):
61
+ raise ValueError("Invalid user id")
62
+ return user_id
63
+
64
+
65
+ def where(**equals: str) -> MetadataFilters:
66
+ """LlamaIndex filters: every key equals its value (values must be safe keys or user ids)."""
67
+ return MetadataFilters(filters=[MetadataFilter(key=k, value=v) for k, v in equals.items()])
68
+
69
+
70
+ def where_not(filters: MetadataFilters, **not_equal: str) -> MetadataFilters:
71
+ extra = [MetadataFilter(key=k, value=v, operator=FilterOperator.NE) for k, v in not_equal.items()]
72
+ return MetadataFilters(filters=[*filters.filters, *extra])
73
+
74
+
75
+ # ---------- The vector stores ----------
76
+ def _store(table: str, indexed: set[tuple[str, str]]):
77
+ store = _stores.get(table)
78
+ if store is not None:
79
+ return store
80
+ with _stores_lock:
81
+ if table not in _stores:
82
+ from llama_index.vector_stores.postgres import PGVectorStore
83
+
84
+ db.init()
85
+ store = PGVectorStore(
86
+ engine=db.engine(),
87
+ async_engine=db.async_engine(),
88
+ table_name=table,
89
+ embed_dim=settings.EMBED_DIM,
90
+ hybrid_search=True, # keyword search (Postgres full text) next to meaning search
91
+ text_search_config="english", # English words are stemmed; other scripts are kept as they are
92
+ use_jsonb=True,
93
+ indexed_metadata_keys=indexed,
94
+ # No approximate (HNSW) index: each search covers one student's or one course's passages,
95
+ # which Postgres scans exactly in milliseconds, and an exact scan never misses a passage.
96
+ )
97
+ store.get_nodes(node_ids=["-"]) # creates the table and its indexes once, before any search
98
+ _stores[table] = store
99
+ return _stores[table]
100
+
101
+
102
+ def notes_store():
103
+ return _store(NOTES_TABLE, {("user_id", "text"), ("path_key", "text"), ("course_key", "text")})
104
+
105
+
106
+ def library_store():
107
+ return _store(LIBRARY_TABLE, {("path_key", "text"), ("subject_key", "text")})
108
+
109
+
110
+ def forget_stores() -> None:
111
+ with _stores_lock:
112
+ _stores.clear()
113
+
114
+
115
+ # ---------- Cutting text into passages ----------
116
+ _splitter = SentenceSplitter(
117
+ chunk_size=settings.CHUNK_CHARS,
118
+ chunk_overlap=settings.CHUNK_OVERLAP_CHARS,
119
+ tokenizer=list, # sizes in characters (the same in every language), not model tokens
120
+ paragraph_separator="\n\n",
121
+ secondary_chunking_regex="[^,.;।。?!?!]+[,.;।。?!?!]?", # also ends sentences at the Hindi danda (।)
122
+ include_metadata=False,
123
+ include_prev_next_rel=False,
124
+ )
125
+
126
+
127
+ def split_text(text: str) -> list[tuple[str, int]]:
128
+ """Passages of about CHUNK_CHARS characters, each with where it starts in `text`."""
129
+ text = clean_text(text)
130
+ if not text.strip():
131
+ return []
132
+ out: list[tuple[str, int]] = []
133
+ prev_start, prev_end = -1, 0
134
+ for node in _splitter.get_nodes_from_documents([Document(text=text)]):
135
+ chunk = node.get_content()
136
+ if not chunk.strip():
137
+ continue
138
+ # LlamaIndex finds a passage's first occurrence, which is wrong for repeated text: search
139
+ # forward instead. A passage starts after the previous one, at most CHUNK_OVERLAP_CHARS back.
140
+ frm = max(prev_start + 1, prev_end - settings.CHUNK_OVERLAP_CHARS)
141
+ start = text.find(chunk, frm)
142
+ if start < 0:
143
+ start = text.find(chunk[:80], frm)
144
+ if start < 0:
145
+ start = max(frm, 0)
146
+ out.append((chunk, start))
147
+ prev_start, prev_end = start, start + len(chunk)
148
+ return out
149
+
150
+
151
+ def _with_embeddings(nodes: list[TextNode]) -> list[TextNode]:
152
+ for i in range(0, len(nodes), EMBED_BATCH):
153
+ batch = nodes[i : i + EMBED_BATCH]
154
+ for node, emb in zip(batch, models.embed_passages([n.text for n in batch])):
155
+ node.embedding = emb
156
+ return nodes
157
+
158
+
159
+ def join_chunks(chunks: list[str], max_overlap: int = 300) -> str:
160
+ """Join ordered passages, dropping the text repeated between neighbours (passages overlap on purpose)."""
161
+ out = ""
162
+ for ch in chunks:
163
+ if not out:
164
+ out = ch
165
+ continue
166
+ overlap = 0
167
+ for k in range(min(max_overlap, len(ch), len(out)), 0, -1):
168
+ if out.endswith(ch[:k]):
169
+ overlap = k
170
+ break
171
+ out += ch[overlap:] if overlap else "\n\n" + ch
172
+ return out
173
+
174
+
175
+ # ---------- A student's notes ----------
176
+ def _note_metadata(user_id: str, path: str, source_file: str) -> dict:
177
+ from backend.file_meta import course_id_from_path, get_entry
178
+
179
+ fm = get_entry(user_id, path)
180
+ course = course_id_from_path(path)
181
+ return {
182
+ "user_id": safe_user_id(str(user_id)),
183
+ "path": str(path or ""),
184
+ "path_key": path_key(path),
185
+ "source_file": str(source_file or ""),
186
+ "course_id": course,
187
+ "course_key": course_key(course),
188
+ "is_primary_authority": int(bool(fm.get("is_primary_authority"))),
189
+ "doc_type": str(fm.get("doc_type") or "other"),
190
+ }
191
+
192
+
193
+ def _replace_note_passages(user_id: str, path: str, nodes: list[TextNode], version: str) -> None:
194
+ """Add the new passages first, then drop older versions: a failure never leaves the file empty."""
195
+ if nodes:
196
+ notes_store().add(nodes)
197
+ db.execute(
198
+ "DELETE FROM data_notes WHERE metadata_->>'user_id' = :u AND metadata_->>'path_key' = :pk "
199
+ "AND coalesce(metadata_->>'ver', '') <> :ver",
200
+ u=user_id,
201
+ pk=path_key(path),
202
+ ver=version,
203
+ )
204
+
205
+
206
+ # Page breaks and markup a passage may start with (Sarvam writes "---" between pages).
207
+ _LEADING_BREAKS = re.compile(r"^(?:\s|-{3,}|\*{3,}|_{3,}|<br\s*/?>|<hr\s*/?>)+", re.IGNORECASE)
208
+
209
+
210
+ def text_start(chunk: str, start: int) -> int:
211
+ """Where the passage's first real words are: its page is the page those words are on."""
212
+ m = _LEADING_BREAKS.match(chunk)
213
+ return start + (m.end() if m and m.end() < len(chunk) else 0)
214
+
215
+
216
+ def index_note(user_id: str, path: str, source_file: str, text: str, page_starts: PageStarts | None = None) -> dict:
217
+ """Make a file searchable (replacing what was stored for it before)."""
218
+ pieces = [
219
+ (chunk, page_at(text_start(chunk, start), page_starts) if page_starts else None)
220
+ for chunk, start in split_text(text)
221
+ ]
222
+ if not pieces:
223
+ return {"chunks_created": 0, "message": "Empty text."}
224
+ count = save_note_passages(user_id, path, source_file, pieces)
225
+ return {"chunks_created": count, "message": f"Saved {count} passages."}
226
+
227
+
228
+ def save_note_passages(user_id: str, path: str, source_file: str, pieces: list[tuple[str, int | None]]) -> int:
229
+ """Store already-cut passages (text, page) of a file, replacing what was stored for it before."""
230
+ base = _note_metadata(user_id, path, source_file)
231
+ version = "v" + uuid.uuid4().hex
232
+ nodes = []
233
+ for i, (chunk, page) in enumerate(pieces):
234
+ meta = {**base, "chunk_index": i, "ver": version}
235
+ if page is not None:
236
+ meta["page"] = int(page)
237
+ nodes.append(TextNode(text=clean_text(chunk), metadata=meta))
238
+ _replace_note_passages(user_id, path, _with_embeddings(nodes), version)
239
+ return len(nodes)
240
+
241
+
242
+ def note_text(user_id: str, path: str) -> str:
243
+ """A file's text rebuilt from its passages, in order, without the repeated overlap."""
244
+ if not path:
245
+ return ""
246
+ notes_store()
247
+ found = db.rows(
248
+ "SELECT text FROM data_notes WHERE metadata_->>'user_id' = :u AND metadata_->>'path_key' = :pk "
249
+ "ORDER BY (metadata_->>'chunk_index')::int",
250
+ u=user_id,
251
+ pk=path_key(path),
252
+ )
253
+ return join_chunks([r["text"].strip() for r in found if (r["text"] or "").strip()])
254
+
255
+
256
+ def note_passages(user_id: str, path: str) -> list[dict]:
257
+ """[{text, metadata}] of one file's passages in order (for checks and admin tools)."""
258
+ notes_store()
259
+ found = db.rows(
260
+ "SELECT text, metadata_ FROM data_notes WHERE metadata_->>'user_id' = :u AND metadata_->>'path_key' = :pk "
261
+ "ORDER BY (metadata_->>'chunk_index')::int",
262
+ u=user_id,
263
+ pk=path_key(path),
264
+ )
265
+ return [{"text": r["text"], "metadata": {k: v for k, v in (r["metadata_"] or {}).items() if not k.startswith("_")}}
266
+ for r in found]
267
+
268
+
269
+ def delete_note_passages(user_id: str, paths: list[str]) -> int:
270
+ """Remove the passages of these files. Returns how many passages were removed."""
271
+ if not paths:
272
+ return 0
273
+ notes_store()
274
+ return db.execute(
275
+ "DELETE FROM data_notes WHERE metadata_->>'user_id' = :u AND metadata_->>'path_key' = ANY(:keys)",
276
+ u=user_id,
277
+ keys=[path_key(p) for p in paths],
278
+ )
279
+
280
+
281
+ def delete_all_note_passages(user_id: str) -> int:
282
+ notes_store()
283
+ return db.execute("DELETE FROM data_notes WHERE metadata_->>'user_id' = :u", u=user_id)
284
+
285
+
286
+ def _rewrite_note(user_id: str, old_path: str, new_path: str, source_file: str | None = None) -> int:
287
+ """Store a file's passages again under new_path and current file details (same text and fingerprints)."""
288
+ old = notes_store().get_nodes(filters=where(user_id=safe_user_id(user_id), path_key=path_key(old_path)))
289
+ if not old:
290
+ return 0
291
+ name = source_file or new_path.replace("\\", "/").rsplit("/", 1)[-1]
292
+ base = _note_metadata(user_id, new_path, name)
293
+ version = "v" + uuid.uuid4().hex
294
+ nodes = []
295
+ for n in old:
296
+ meta = {**base, "chunk_index": int(n.metadata.get("chunk_index") or 0), "ver": version}
297
+ if n.metadata.get("page") is not None:
298
+ meta["page"] = int(n.metadata["page"])
299
+ nodes.append(TextNode(text=n.get_content(), metadata=meta, embedding=n.embedding))
300
+ if any(n.embedding is None for n in nodes):
301
+ _with_embeddings(nodes)
302
+ if old_path == new_path:
303
+ _replace_note_passages(user_id, new_path, nodes, version)
304
+ else:
305
+ notes_store().add(nodes)
306
+ delete_note_passages(user_id, [old_path])
307
+ return len(nodes)
308
+
309
+
310
+ def move_note(user_id: str, old_path: str, new_path: str, source_file: str | None = None) -> int:
311
+ """Move a file's passages to its new path (rename or move). Returns how many were moved."""
312
+ if old_path != new_path:
313
+ delete_note_passages(user_id, [new_path]) # leftovers from a deleted file of that name
314
+ return _rewrite_note(user_id, old_path, new_path, source_file)
315
+
316
+
317
+ def move_folder_notes(user_id: str, file_paths: list[str], old_prefix: str, new_prefix: str) -> int:
318
+ """Move the passages of each file under old_prefix (paths from the folder tree) to new_prefix."""
319
+ old_prefix = old_prefix.replace("\\", "/").strip("/")
320
+ new_prefix = new_prefix.replace("\\", "/").strip("/")
321
+ moved = 0
322
+ for p in file_paths:
323
+ if p == old_prefix or p.startswith(old_prefix + "/"):
324
+ moved += move_note(user_id, p, new_prefix + p[len(old_prefix):])
325
+ return moved
326
+
327
+
328
+ def refresh_note_details(user_id: str, paths: list[str]) -> int:
329
+ """Store the current file details (e.g. "main source") on each passage of these files."""
330
+ updated = 0
331
+ for p in paths:
332
+ try:
333
+ updated += _rewrite_note(user_id, p, p)
334
+ except Exception:
335
+ logger.warning("Updating passage details failed for %s", p, exc_info=True)
336
+ return updated
337
+
338
+
339
+ # ---------- The shared course library ----------
340
+ def index_library_file(path: str, base: dict, pieces: list[tuple[str, int | None, float | None]]) -> int:
341
+ """
342
+ Replace the passages of one library PDF. `pieces` are (text, page, y) where y is how far down the
343
+ page the passage starts (0 = top, 1 = bottom), so a viewer can scroll to it.
344
+ """
345
+ version = "v" + uuid.uuid4().hex
346
+ common = {**base, "path": path, "path_key": path_key(path), "subject_key": subject_key(base.get("subject") or "")}
347
+ nodes = []
348
+ for i, (text, page, y) in enumerate(pieces):
349
+ meta = {**common, "chunk_index": i, "ver": version}
350
+ if page is not None:
351
+ meta["page"] = int(page)
352
+ if y is not None:
353
+ meta["y"] = round(float(y), 4)
354
+ nodes.append(TextNode(text=clean_text(text), metadata=meta))
355
+ if nodes:
356
+ library_store().add(_with_embeddings(nodes))
357
+ db.execute(
358
+ "DELETE FROM data_library WHERE metadata_->>'path_key' = :pk AND coalesce(metadata_->>'ver', '') <> :ver",
359
+ pk=path_key(path),
360
+ ver=version,
361
+ )
362
+ return len(nodes)
363
+
364
+
365
+ def delete_library_file(path: str) -> int:
366
+ library_store()
367
+ return db.execute("DELETE FROM data_library WHERE metadata_->>'path_key' = :pk", pk=path_key(path))
368
+
369
+
370
+ def library_passage_count(path: str) -> int:
371
+ library_store()
372
+ count = db.scalar("SELECT count(*) FROM data_library WHERE metadata_->>'path_key' = :pk", pk=path_key(path))
373
+ return int(count or 0)
374
+
375
+
376
+ def library_passages(path: str) -> list[dict]:
377
+ """[{text, metadata}] of one library PDF in order (for checks and admin tools)."""
378
+ library_store()
379
+ found = db.rows(
380
+ "SELECT text, metadata_ FROM data_library WHERE metadata_->>'path_key' = :pk "
381
+ "ORDER BY (metadata_->>'chunk_index')::int",
382
+ pk=path_key(path),
383
+ )
384
+ return [{"text": r["text"], "metadata": {k: v for k, v in (r["metadata_"] or {}).items() if not k.startswith("_")}}
385
+ for r in found]
backend/pipeline/models.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The three AI models the pipeline uses, in one place (all through LlamaIndex):
3
+
4
+ - Search model (EMBED_MODEL): turns each passage and each question into a "meaning fingerprint",
5
+ a list of numbers. Runs on our server, free. Multilingual: Hindi questions find English notes.
6
+ - Re-checking model (RERANK_MODEL): reads the question with each candidate passage and scores how
7
+ well the passage answers it, from 0 to 1. Runs on our server, free.
8
+ - Language model: writes answers, flashcards, quizzes and summaries. Sarvam AI by default; any
9
+ service with an OpenAI-style chat API can be used instead (LLM_PROVIDER=openai_like), e.g.
10
+ DeepSeek on NVIDIA, DeepInfra or OpenRouter.
11
+
12
+ To try another model, change the setting (see settings.py) and run the answer-quality test before
13
+ and after (scripts/answer_quality.py).
14
+ """
15
+ import math
16
+ import os
17
+ import threading
18
+
19
+ from backend import settings
20
+
21
+ # Sarvam's models (https://docs.sarvam.ai). sarvam-30b was retired in 2026.
22
+ SARVAM_DEFAULT_MODEL = "sarvam-105b"
23
+
24
+ # Tests plug in an httpx client with a fake transport here; None = the SDK's own client.
25
+ HTTP_CLIENT = None
26
+
27
+ _lock = threading.Lock()
28
+ _embedder = None
29
+ _reranker = None
30
+ _llms: dict[tuple, object] = {}
31
+
32
+
33
+ # ---------- Search model ----------
34
+ def embedder():
35
+ """LlamaIndex embedding model, loaded once per process (loading takes a few seconds)."""
36
+ global _embedder
37
+ if _embedder is None:
38
+ with _lock:
39
+ if _embedder is None:
40
+ from llama_index.embeddings.huggingface import HuggingFaceEmbedding
41
+
42
+ # E5 models are trained with these prefixes; other models get none.
43
+ e5 = "e5" in settings.EMBED_MODEL.lower()
44
+ _embedder = HuggingFaceEmbedding(
45
+ model_name=settings.EMBED_MODEL,
46
+ query_instruction="query: " if e5 else None,
47
+ text_instruction="passage: " if e5 else None,
48
+ normalize=True,
49
+ embed_batch_size=32,
50
+ )
51
+ return _embedder
52
+
53
+
54
+ def embed_passages(texts: list[str]) -> list[list[float]]:
55
+ """Fingerprints for passages of notes (unit length, so a dot product is cosine similarity)."""
56
+ if not texts:
57
+ return []
58
+ return embedder().get_text_embedding_batch(list(texts))
59
+
60
+
61
+ def embed_question(text: str) -> list[float]:
62
+ return embedder().get_query_embedding(text)
63
+
64
+
65
+ # ---------- Re-checking model ----------
66
+ def reranker():
67
+ """LlamaIndex's cross-encoder re-ranker, or None when RERANK_MODEL is empty."""
68
+ global _reranker
69
+ if not settings.RERANK_MODEL:
70
+ return None
71
+ if _reranker is None:
72
+ with _lock:
73
+ if _reranker is None:
74
+ from llama_index.core.postprocessor import SentenceTransformerRerank
75
+
76
+ _reranker = SentenceTransformerRerank(model=settings.RERANK_MODEL, top_n=1000)
77
+ return _reranker
78
+
79
+
80
+ def relevance(question: str, texts: list[str]) -> list[float] | None:
81
+ """
82
+ How well each text answers the question, 0..1 (None when re-checking is turned off).
83
+ The model gives a raw score; the logistic function maps it to 0..1 (0.5 = undecided).
84
+ """
85
+ model = reranker()
86
+ if model is None or not texts:
87
+ return None if model is None else []
88
+ from llama_index.core.schema import NodeWithScore, QueryBundle, TextNode
89
+
90
+ nodes = [NodeWithScore(node=TextNode(text=t, id_=str(i)), score=0.0) for i, t in enumerate(texts)]
91
+ ranked = model.postprocess_nodes(nodes, query_bundle=QueryBundle(question))
92
+ by_id = {n.node.node_id: float(n.score or 0.0) for n in ranked}
93
+ return [_logistic(by_id.get(str(i), -20.0)) for i in range(len(texts))]
94
+
95
+
96
+ def _logistic(x: float) -> float:
97
+ return 1.0 / (1.0 + math.exp(-max(min(x, 40.0), -40.0)))
98
+
99
+
100
+ def warm_up() -> None:
101
+ """Load the local models now (in the background at start-up) so the first question is fast."""
102
+ embed_question("warm up")
103
+ relevance("warm up", ["warm up"])
104
+
105
+
106
+ # ---------- Language model ----------
107
+ def sarvam_api_base() -> str:
108
+ base = (os.getenv("SARVAM_API_BASE") or "").strip().rstrip("/") or "https://api.sarvam.ai"
109
+ return base if base.endswith("/v1") else base + "/v1"
110
+
111
+
112
+ def sarvam_model(purpose: str) -> str:
113
+ """Model for answers ("answer") or for study tools and helpers ("study")."""
114
+ name = "SARVAM_MODEL_RAG" if purpose == "answer" else "SARVAM_MODEL_STUDY"
115
+ return (os.getenv(name) or "").strip() or SARVAM_DEFAULT_MODEL
116
+
117
+
118
+ def llm(purpose: str, max_tokens: int, temperature: float, reasoning: str | None = None, model: str | None = None):
119
+ """
120
+ A LlamaIndex chat model. `reasoning`: None = the model's default, "off" = no thinking (fast,
121
+ cheap: study tools), or low | medium | high (Sarvam's reasoning effort).
122
+ """
123
+ key = (settings.LLM_PROVIDER, purpose, max_tokens, temperature, reasoning, model, id(HTTP_CLIENT))
124
+ with _lock:
125
+ if key in _llms:
126
+ return _llms[key]
127
+ extra = {}
128
+ if reasoning == "off":
129
+ extra["reasoning_effort"] = None # Sarvam: an explicit null turns reasoning off
130
+ elif reasoning:
131
+ extra["reasoning_effort"] = reasoning
132
+ if settings.LLM_PROVIDER == "openai_like":
133
+ from llama_index.llms.openai_like import OpenAILike
134
+
135
+ # Services differ in how thinking is switched off; the request fields come from the settings.
136
+ thinking_off = reasoning == "off" and settings.LLM_THINKING_OFF
137
+ instance = OpenAILike(
138
+ model=model or settings.LLM_MODEL,
139
+ api_base=settings.LLM_API_BASE,
140
+ api_key=settings.LLM_API_KEY,
141
+ is_chat_model=True,
142
+ context_window=128000,
143
+ max_tokens=max_tokens,
144
+ temperature=temperature,
145
+ additional_kwargs={"extra_body": settings.LLM_THINKING_OFF} if thinking_off else {},
146
+ timeout=300.0,
147
+ max_retries=2,
148
+ http_client=HTTP_CLIENT,
149
+ )
150
+ else:
151
+ from llama_index.llms.sarvam import Sarvam
152
+
153
+ from backend.ocr import sarvam_api_key
154
+
155
+ instance = Sarvam(
156
+ model=model or sarvam_model(purpose),
157
+ api_key=sarvam_api_key() or "",
158
+ api_base=sarvam_api_base(),
159
+ max_tokens=max_tokens,
160
+ temperature=temperature,
161
+ additional_kwargs=extra,
162
+ context_window=128000,
163
+ timeout=300.0,
164
+ max_retries=2,
165
+ http_client=HTTP_CLIENT,
166
+ )
167
+ with _lock:
168
+ _llms[key] = instance
169
+ return instance
170
+
171
+
172
+ def llm_configured() -> bool:
173
+ if settings.LLM_PROVIDER == "openai_like":
174
+ return bool(settings.LLM_API_BASE and settings.LLM_MODEL)
175
+ from backend.ocr import sarvam_api_key
176
+
177
+ return bool(sarvam_api_key())
178
+
179
+
180
+ def forget_llms() -> None:
181
+ """Drop cached model clients (tests change settings between cases)."""
182
+ with _lock:
183
+ _llms.clear()
backend/pipeline/retrieval.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Finding the passages that answer a question (the "retrieval" step of the pipeline).
3
+
4
+ Places are searched in this order, and the first one with a relevant enough passage is used:
5
+ chat uploads (+ button) → the shared course PDF that is open and the rest of its course (Interview.ai)
6
+ → the open file → other files in the same course folder → all other notes. If no place is relevant
7
+ enough, the best-scoring one is used (the answer then says what is beyond the notes).
8
+
9
+ In each place:
10
+ 1. LlamaIndex runs a hybrid search in Postgres: the passages closest in meaning to the question
11
+ (fingerprints) plus the passages sharing its keywords (full-text search), CANDIDATES_PER_SEARCH each.
12
+ 2. The re-checking model scores every candidate 0..1 for how well it answers the question. Scores
13
+ are comparable across places, so "relevant enough" means the same thing everywhere.
14
+ A place is only searched when the places before it had nothing relevant enough.
15
+ """
16
+ import re
17
+ from dataclasses import dataclass, field
18
+ from typing import Callable
19
+
20
+ import numpy as np
21
+ from llama_index.core.vector_stores.types import VectorStoreQuery, VectorStoreQueryMode
22
+
23
+ from backend import library, settings
24
+ from backend.pipeline import indexing, models
25
+ from backend.settings import (
26
+ CANDIDATES_PER_SEARCH,
27
+ MAIN_SOURCE_BOOST,
28
+ MIN_KEEP_SCORE,
29
+ MIN_SCORE_ALL_NOTES,
30
+ MIN_SCORE_CHAT_UPLOAD,
31
+ MIN_SCORE_COURSE,
32
+ MIN_SCORE_LIBRARY_FILE,
33
+ MIN_SCORE_LIBRARY_SUBJECT,
34
+ MIN_SCORE_OPEN_FILE,
35
+ SOURCE_SCORE_WINDOW,
36
+ )
37
+
38
+ MAX_SELECTED = 8
39
+ FALLBACK_KEEP = 3 # when nothing is relevant, the best few still go to the AI
40
+ OPEN_LIBRARY_FILE_LEAD = 0.10 # ranking lead for the course PDF the student has open
41
+ OPEN_PDF_KEEP = 3 # passages of the open PDF always sent when it is nearly as relevant...
42
+ OPEN_PDF_KEEP_GAP = 0.25 # ...as the best passage of its course (within this much)
43
+ _INTERNAL_KEYS = ("ver", "path_key", "course_key", "subject_key")
44
+
45
+
46
+ @dataclass
47
+ class SearchResult:
48
+ stage: str = ""
49
+ selected: list[dict] = field(default_factory=list)
50
+ best_scores: dict[str, float] = field(default_factory=dict)
51
+
52
+ def context(self) -> str:
53
+ parts = []
54
+ for d in self.selected:
55
+ content = (d.get("content") or "").strip()
56
+ if not content:
57
+ continue
58
+ md = d.get("metadata") or {}
59
+ label = md.get("path") or "chunk"
60
+ if md.get("library"):
61
+ label = f"Course notes: {md.get('label') or label}"
62
+ # Most course PDFs are one long page: a page number would only add noise there.
63
+ if md.get("page") and int(md.get("pages") or 2) > 1:
64
+ label += f", page {md['page']}"
65
+ if md.get("is_primary_authority"):
66
+ label += " (main source)"
67
+ parts.append(f"[{label}]\n{content[:1200]}")
68
+ return "\n\n".join(parts)
69
+
70
+ def source_documents(self) -> list[dict]:
71
+ return [{k: v for k, v in d.items() if k != "_score"} for d in self.selected]
72
+
73
+
74
+ # ---------- Candidates ----------
75
+ @dataclass
76
+ class Question:
77
+ text: str # what the re-checking model compares passages with
78
+ keywords: str # words for the keyword search
79
+ embedding: list[float] # the question's meaning fingerprint
80
+
81
+
82
+ def _public(metadata: dict) -> dict:
83
+ return {k: v for k, v in (metadata or {}).items() if k not in _INTERNAL_KEYS}
84
+
85
+
86
+ def hybrid_search(store, question: Question, filters, k: int = CANDIDATES_PER_SEARCH) -> list[dict]:
87
+ """
88
+ Candidates from one LlamaIndex vector store: by meaning and by keywords (or by meaning only when
89
+ re-checking is off, so the scores stay cosine similarities).
90
+ """
91
+ hybrid = models.reranker() is not None
92
+ res = store.query(
93
+ VectorStoreQuery(
94
+ query_embedding=question.embedding,
95
+ query_str=question.keywords,
96
+ similarity_top_k=k,
97
+ sparse_top_k=k,
98
+ mode=VectorStoreQueryMode.HYBRID if hybrid and question.keywords else VectorStoreQueryMode.DEFAULT,
99
+ filters=filters,
100
+ )
101
+ )
102
+ sims = list(res.similarities or [])
103
+ out = []
104
+ for i, node in enumerate(res.nodes or []):
105
+ content = node.get_content()
106
+ if not content.strip():
107
+ continue
108
+ score = float(sims[i]) if i < len(sims) and sims[i] is not None and not hybrid else 0.0
109
+ out.append({"id": node.node_id, "content": content, "metadata": _public(node.metadata), "_score": score})
110
+ return out
111
+
112
+
113
+ _WORD = re.compile(r"\w{3,}")
114
+ _COMMON = {"the", "and", "for", "what", "which", "who", "how", "why", "when", "where", "this", "that", "with",
115
+ "from", "are", "was", "were", "does", "did", "can", "about", "explain", "tell", "give", "into"}
116
+
117
+
118
+ def _keyword_set(text: str) -> set[str]:
119
+ return {w for w in _WORD.findall((text or "").lower()) if w not in _COMMON}
120
+
121
+
122
+ def _chat_upload_candidates(ephemeral: list[dict], question: Question, k: int = CANDIDATES_PER_SEARCH) -> list[dict]:
123
+ """
124
+ Passages of files attached to this chat (+ button; kept in memory only): per file, the closest
125
+ by meaning and the ones sharing the most keywords with the question, like hybrid_search.
126
+ """
127
+ q_vec = np.asarray(question.embedding, dtype=np.float32)
128
+ words = _keyword_set(question.keywords)
129
+ out: list[dict] = []
130
+ for i, it in enumerate(ephemeral):
131
+ chunks = it.get("chunks") or []
132
+ embs = it.get("embeddings")
133
+ if not chunks or embs is None or len(embs) != len(chunks):
134
+ continue
135
+ sims = embs @ q_vec
136
+ by_meaning = [int(j) for j in np.argsort(-sims)]
137
+ hits = [len(words & _keyword_set(c)) for c in chunks] if words else [0] * len(chunks)
138
+ by_keyword = [j for j in sorted(range(len(chunks)), key=lambda j: -hits[j]) if hits[j] > 0]
139
+ picked: list[int] = []
140
+ seen_text: set[str] = set()
141
+
142
+ def take(order: list[int]) -> None:
143
+ added = 0
144
+ for j in order:
145
+ if added == k:
146
+ return
147
+ if chunks[j] not in seen_text: # repeated text (copied pages) counts once
148
+ seen_text.add(chunks[j])
149
+ picked.append(j)
150
+ added += 1
151
+
152
+ take(by_meaning)
153
+ take(by_keyword)
154
+ for j in picked:
155
+ out.append({
156
+ "id": f"ephemeral|{i}|{j}",
157
+ "content": chunks[j],
158
+ "metadata": {
159
+ "path": f"[chat-upload] {it.get('name') or 'file'}",
160
+ "source_file": it.get("name") or "chat-upload",
161
+ "ephemeral_chat_upload": 1,
162
+ },
163
+ "_score": float(sims[j]),
164
+ })
165
+ return out
166
+
167
+
168
+ # ---------- Scoring ----------
169
+ def keyword_text(*parts: str) -> str:
170
+ """Text for the keyword search (LlamaIndex drops punctuation and joins the words with OR)."""
171
+ return re.sub(r"\s+", " ", " ".join(p or "" for p in parts)).strip()[:1000]
172
+
173
+
174
+ def score(question: Question, docs: list[dict]) -> list[dict]:
175
+ """Re-check every candidate (0..1), add the main-source boost, best first. Duplicates are dropped."""
176
+ seen, unique = set(), []
177
+ for d in docs:
178
+ if d["id"] not in seen:
179
+ seen.add(d["id"])
180
+ unique.append(d)
181
+ rel = models.relevance(question.text, [d["content"] for d in unique])
182
+ out = []
183
+ for i, d in enumerate(unique):
184
+ s = rel[i] if rel is not None else d["_score"]
185
+ if (d.get("metadata") or {}).get("is_primary_authority"):
186
+ s += MAIN_SOURCE_BOOST
187
+ out.append({**d, "_score": float(s)})
188
+ out.sort(key=lambda d: d["_score"], reverse=True)
189
+ return out
190
+
191
+
192
+ def _closest(docs: list[dict]) -> list[dict]:
193
+ """The best passages of a place: those close to its top match (at most MAX_SELECTED)."""
194
+ if not docs:
195
+ return []
196
+ floor = max(MIN_KEEP_SCORE, docs[0]["_score"] - SOURCE_SCORE_WINDOW)
197
+ keep = [d for d in docs if d["_score"] >= floor][:MAX_SELECTED]
198
+ return keep or docs[:FALLBACK_KEEP]
199
+
200
+
201
+ def course_of(opened: str, course_path: str) -> str:
202
+ course = course_path or ""
203
+ if not course and opened:
204
+ course = opened.split("/", 1)[0] if "/" in opened else opened
205
+ return course.split("/", 1)[0] if course else ""
206
+
207
+
208
+ # ---------- The search ----------
209
+ @dataclass
210
+ class _Stage:
211
+ name: str
212
+ min_score: float
213
+ find: Callable[[], list[dict]] # candidates, already scored and sorted
214
+
215
+
216
+ def find_context(
217
+ user_id: str,
218
+ question: str,
219
+ all_paths: list[str],
220
+ opened: str,
221
+ course: str,
222
+ ephemeral: list[dict],
223
+ include_other_notes: bool = True,
224
+ library_path: str = "",
225
+ keywords: str | None = None,
226
+ ) -> SearchResult:
227
+ """
228
+ The passages to answer `question` from. `keywords` (default: the question) feed the keyword search;
229
+ a follow-up question should already be rewritten to stand on its own (see generation.py).
230
+ """
231
+ user_id = indexing.safe_user_id(user_id)
232
+ q_emb = models.embed_question(question)
233
+ q = Question(text=question, keywords=keyword_text(keywords if keywords is not None else question), embedding=q_emb)
234
+ all_set = set(all_paths)
235
+ notes = indexing.notes_store()
236
+ mine = {"user_id": user_id}
237
+
238
+ def in_tree(docs: list[dict]) -> list[dict]:
239
+ # Passages of files no longer in the folder tree never show up (e.g. a delete that failed halfway).
240
+ return [d for d in docs if (d.get("metadata") or {}).get("path") in all_set]
241
+
242
+ def chat_uploads() -> list[dict]:
243
+ return score(q, _chat_upload_candidates(ephemeral, q))
244
+
245
+ def open_file() -> list[dict]:
246
+ if opened not in all_set:
247
+ return []
248
+ return score(q, in_tree(hybrid_search(notes, q, indexing.where(**mine, path_key=indexing.path_key(opened)))))
249
+
250
+ def same_course() -> list[dict]:
251
+ if not (include_other_notes and all_paths and course):
252
+ return []
253
+ filters = indexing.where(**mine, course_key=indexing.course_key(course))
254
+ if opened:
255
+ filters = indexing.where_not(filters, path_key=indexing.path_key(opened))
256
+ return score(q, in_tree(hybrid_search(notes, q, filters)))
257
+
258
+ def other_notes() -> list[dict]:
259
+ if not (include_other_notes and all_paths):
260
+ return []
261
+ filters = indexing.where(**mine)
262
+ if course:
263
+ filters = indexing.where_not(filters, course_key=indexing.course_key(course))
264
+ elif opened:
265
+ filters = indexing.where_not(filters, path_key=indexing.path_key(opened))
266
+ return score(q, in_tree(hybrid_search(notes, q, filters)))
267
+
268
+ # Shared course library: the open course PDF and the other PDFs of its course, ranked together
269
+ # with a small lead for the open PDF, so a lecture that clearly answers the question wins over a
270
+ # loosely related open PDF.
271
+ lib_file, lib_subject = library.scope_of(library_path)
272
+ lib: dict[str, list[dict]] = {"file": [], "subject": []}
273
+
274
+ def course_library() -> list[dict]:
275
+ if not (settings.LIBRARY_ENABLED and lib_subject):
276
+ return []
277
+ store = indexing.library_store()
278
+ if lib_file:
279
+ lib["file"] = hybrid_search(store, q, indexing.where(path_key=indexing.path_key(lib_file)))
280
+ if include_other_notes or not lib_file:
281
+ filters = indexing.where(subject_key=indexing.subject_key(lib_subject))
282
+ if lib_file:
283
+ filters = indexing.where_not(filters, path_key=indexing.path_key(lib_file))
284
+ lib["subject"] = hybrid_search(store, q, filters)
285
+ ranked = score(q, lib["file"] + lib["subject"])
286
+ file_ids = {d["id"] for d in lib["file"]}
287
+ lib["file"] = [d for d in ranked if d["id"] in file_ids]
288
+ lib["subject"] = [d for d in ranked if d["id"] not in file_ids]
289
+ led = [{**d, "_score": d["_score"] + OPEN_LIBRARY_FILE_LEAD} if d["id"] in file_ids else d for d in ranked]
290
+ return sorted(led, key=lambda d: d["_score"], reverse=True)
291
+
292
+ stages = [
293
+ _Stage("ephemeral", MIN_SCORE_CHAT_UPLOAD, chat_uploads),
294
+ _Stage("library", 0.0, course_library), # named after its best passage's file, below
295
+ _Stage("opened", MIN_SCORE_OPEN_FILE, open_file),
296
+ _Stage("course", MIN_SCORE_COURSE, same_course),
297
+ _Stage("all_notes", MIN_SCORE_ALL_NOTES, other_notes),
298
+ ]
299
+ result = SearchResult(best_scores={n: -1.0 for n in ("ephemeral", "library_file", "library_subject", "opened", "course", "all_notes")})
300
+ found: list[tuple[str, list[dict]]] = []
301
+ for stage in stages:
302
+ docs = stage.find()
303
+ if not docs:
304
+ continue
305
+ name = stage.name
306
+ relevant = docs[0]["_score"] >= stage.min_score
307
+ if name == "library":
308
+ name = "library_file" if docs[0]["metadata"].get("path") == lib_file else "library_subject"
309
+ # Judged on the passages' own scores: the open PDF's lead only changes the order.
310
+ relevant = bool(lib["file"]) and lib["file"][0]["_score"] >= MIN_SCORE_LIBRARY_FILE or (
311
+ bool(lib["subject"]) and lib["subject"][0]["_score"] >= MIN_SCORE_LIBRARY_SUBJECT
312
+ )
313
+ for part in ("file", "subject"):
314
+ if lib[part]:
315
+ result.best_scores[f"library_{part}"] = round(lib[part][0]["_score"], 4)
316
+ else:
317
+ result.best_scores[name] = round(docs[0]["_score"], 4)
318
+ found.append((name, docs))
319
+ if relevant:
320
+ result.stage, result.selected = name, _closest(docs)
321
+ _keep_open_pdf(result, lib["file"], lib["subject"])
322
+ return result
323
+ # A question about a course PDF never falls back to loosely related notes of the student's own
324
+ # (e.g. sample physics notes for a maths course): only the course library itself.
325
+ fallback = [f for f in found if f[0].startswith("library")] if lib_subject else found
326
+ if fallback:
327
+ result.stage, docs = max(fallback, key=lambda f: f[1][0]["_score"])
328
+ result.selected = _closest(docs)
329
+ _keep_open_pdf(result, lib["file"], lib["subject"])
330
+ return result
331
+
332
+
333
+ def _keep_open_pdf(result: SearchResult, file_docs: list[dict], subject_docs: list[dict]) -> None:
334
+ """
335
+ The student asked while reading a course PDF: make sure its best passages reach the answer when
336
+ it is nearly as relevant as the rest of the course, even if many other passages score a little
337
+ higher (e.g. exam answers that all mention "time complexity"). They go first in the context.
338
+ """
339
+ if not file_docs or not result.stage.startswith("library"):
340
+ return
341
+ best_other = subject_docs[0]["_score"] if subject_docs else -1.0
342
+ if file_docs[0]["_score"] < max(MIN_SCORE_LIBRARY_FILE, best_other - OPEN_PDF_KEEP_GAP):
343
+ return
344
+ keep = [d for d in file_docs[:OPEN_PDF_KEEP] if d["_score"] >= MIN_SCORE_LIBRARY_FILE]
345
+ kept_ids = {d["id"] for d in keep}
346
+ result.selected = (keep + [d for d in result.selected if d["id"] not in kept_ids])[:MAX_SELECTED]
backend/preferences.py CHANGED
@@ -3,7 +3,7 @@ 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
 
3
  import time
4
 
5
  from backend import mailer
6
+ from backend.store import user_get_by_id, user_update_metadata
7
  from backend.settings import ANSWER_LANGUAGES, REMINDERS_ENABLED
8
 
9
  _CACHE_SECONDS = 60
backend/reminders.py CHANGED
@@ -11,7 +11,7 @@ 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
 
@@ -28,8 +28,8 @@ 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
 
@@ -46,7 +46,8 @@ def send_due_reminders(now: float | None = None) -> int:
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()))
 
11
  import time
12
 
13
  from backend import alerts, mailer, settings, study_store, usage
14
+ from backend.store import user_update_metadata, users_where
15
 
16
  logger = logging.getLogger(__name__)
17
 
 
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 Study AI. A few minutes now saves a lot of re-reading later.\n\n"
32
+ f"Open Study AI: {settings.FRONTEND_URL}#study\n\n"
33
  "You get this email because daily reminders are on. You can turn them off in Account settings."
34
  )
35
 
 
46
  sent = 0
47
  for user in users_where({"pref_reminders": 1}):
48
  meta = user["meta"]
49
+ # Only confirmed addresses: an unconfirmed one may belong to someone else.
50
+ if meta.get("reminder_sent_day") == today or not user.get("email") or not user["email_verified"]:
51
  continue
52
  try:
53
  due = study_store.due_count(user["user_id"], until=_end_of_day(local.date()))
backend/routes/account.py CHANGED
@@ -1,19 +1,21 @@
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,
@@ -22,29 +24,15 @@ from backend import (
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
@@ -58,7 +46,7 @@ from backend.settings import (
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
 
@@ -66,31 +54,72 @@ 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")
@@ -100,10 +129,9 @@ def register(
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]
@@ -112,23 +140,84 @@ def register(
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")
@@ -138,40 +227,50 @@ def login(request: Request, email: str = Form(...), password: str = Form(...)):
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
 
@@ -208,59 +307,97 @@ def change_password(
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
 
@@ -271,9 +408,8 @@ def reset_password(request: Request, token: str = Form(...), new_password: str =
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."})
 
1
+ """Sign-up, sign-in, sign-out, password changes/resets, email checks and account deletion.
2
+
3
+ Accounts and passwords live in Neon Auth (backend/neon_auth.py); these routes call it for the website
4
+ and keep Study AI's own details (privacy acceptance, preferences) in the users table.
5
+ """
6
  import logging
7
  import re
 
8
  import time
9
  import uuid
10
 
11
+ from fastapi import APIRouter, Form, HTTPException, Request
 
12
  from fastapi.responses import JSONResponse
13
 
14
  from backend import (
15
  chat_cache,
16
  feedback,
17
+ neon_auth,
18
+ originals,
19
  preferences,
20
  rate_limit,
21
  settings,
 
24
  uploads,
25
  usage,
26
  )
27
+ from backend.auth import SESSION_HEADER, forget_user, signed_in_user
28
+ from backend.pipeline.indexing import delete_all_note_passages
29
+ from backend.store import (
30
+ delete_user_vfs,
 
 
 
 
 
 
 
31
  onenote_token_delete,
 
 
 
 
32
  user_create,
33
  user_delete,
34
  user_document_delete_many,
 
 
35
  user_get_by_id,
 
36
  )
37
  from backend.deps import SignedInUser
38
  from backend.rate_limit import client_ip
 
46
  LIMIT_PASSWORD_CHECK_PER_USER,
47
  LIMIT_REGISTER_PER_IP,
48
  LIMIT_RESET_PER_IP,
49
+ MAX_PASSWORD_LEN,
50
  MIN_PASSWORD_LEN,
51
  )
52
 
 
54
  router = APIRouter()
55
 
56
  _EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
57
+ LIMIT_EMAIL_CODES_PER_USER = (5, 3600)
58
 
59
 
60
  def _error(message: str, status_code: int = 400) -> JSONResponse:
61
  return JSONResponse({"error": message}, status_code=status_code)
62
 
63
 
64
+ def _auth_error(e: neon_auth.AuthError) -> JSONResponse:
65
+ return _error(e.message, e.status)
66
+
67
+
68
  def _password_problem(password: str) -> str | None:
69
  if len(password) < MIN_PASSWORD_LEN:
70
  return f"Password must be at least {MIN_PASSWORD_LEN} characters."
71
+ if len(password) > MAX_PASSWORD_LEN:
72
+ return f"Password is too long (maximum {MAX_PASSWORD_LEN} characters)."
73
  return None
74
 
75
 
76
+ def _database_error(action: str) -> JSONResponse:
 
77
  logger.exception("%s failed", action)
 
 
78
  return _error(f"{action} failed because of a server error. Please try again.", 500)
79
 
80
 
81
+ def _signed_in(signin: neon_auth.SignIn, name: str = "") -> JSONResponse:
82
+ return JSONResponse({
83
+ "session_id": signin.session,
84
+ "user_id": signin.user.id,
85
+ "name": name or signin.user.name or signin.user.email.split("@")[0],
86
+ })
87
+
88
+
89
+ def _accepted(value: str) -> bool:
90
+ return (value or "").strip().lower() in ("1", "true", "yes", "on")
91
+
92
+
93
+ def _start_account(user: neon_auth.User, name: str) -> None:
94
+ """Add the Study AI account for a Neon Auth account (the student accepted the privacy note just now)."""
95
+ added = user_create(
96
+ user.id,
97
+ user.email,
98
+ name,
99
+ user.email_verified,
100
+ privacy_accepted_at=int(time.time()),
101
+ privacy_version=settings.PRIVACY_VERSION,
102
+ )
103
+ if added and settings.STARTER_NOTES:
104
+ starter_notes.add_starter_notes_in_background(user.id)
105
+
106
+
107
+ def _send_code(email: str) -> None:
108
+ """Email a new confirmation code, unless this address got several already (then the last one still works)."""
109
+ try:
110
+ rate_limit.check("signup-code", email, *LIMIT_EMAIL_CODES_PER_USER)
111
+ except HTTPException:
112
+ return
113
+ neon_auth.send_verification_code(email)
114
+
115
+
116
+ def _confirm_email(email: str, status_code: int = 200) -> JSONResponse:
117
+ """Neon wants the email confirmed before signing in: the website asks for the emailed code."""
118
+ return JSONResponse({
119
+ "confirm_email": True,
120
+ "email": email,
121
+ "error" if status_code >= 400 else "message": f"Please confirm your email: enter the code we sent to {email}.",
122
+ }, status_code=status_code)
123
 
124
 
125
  @router.post("/register")
 
129
  password: str = Form(...),
130
  name: str = Form(""),
131
  accepted_privacy: str = Form(""),
 
132
  ):
133
  rate_limit.check("register", client_ip(request), *LIMIT_REGISTER_PER_IP)
134
+ if not _accepted(accepted_privacy):
135
  return _error("Please read and accept the privacy note.")
136
  email = (email or "").strip().lower()
137
  name = (name or "").strip()[:80]
 
140
  problem = _password_problem(password)
141
  if problem:
142
  return _error(problem)
143
+ display_name = name or email.split("@")[0]
144
  try:
145
+ signin = neon_auth.sign_up(email, password, display_name)
146
+ except neon_auth.AuthError as e:
147
+ if e.code not in ("USER_ALREADY_EXISTS", "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL"):
148
+ return _auth_error(e)
149
+ # The Neon account may exist without a Study AI account (an earlier sign-up that didn't
150
+ # finish, or one still waiting for its email code): with the right password, carry on.
151
+ try:
152
+ signin = neon_auth.sign_in(email, password)
153
+ except neon_auth.AuthError as e2:
154
+ if e2.code != "EMAIL_NOT_VERIFIED":
155
+ return _error("Email already registered.")
156
+ try:
157
+ _send_code(email)
158
+ except neon_auth.AuthError as e3:
159
+ return _auth_error(e3)
160
+ return _confirm_email(email) # the account is made once the code is confirmed
161
+ if user_get_by_id(signin.user.id):
162
+ neon_auth.sign_out(signin.session)
163
  return _error("Email already registered.")
164
+ try:
165
+ _start_account(signin.user, display_name)
166
+ except Exception:
167
+ if signin.session:
168
+ neon_auth.sign_out(signin.session)
169
+ return _database_error("Sign-up")
170
+ if not signin.session:
171
+ return _confirm_email(email) # Neon has emailed the code
172
+ return _signed_in(signin, display_name)
173
+
174
+
175
+ @router.post("/register/confirm")
176
+ def confirm_sign_up(
177
+ request: Request,
178
+ email: str = Form(...),
179
+ code: str = Form(...),
180
+ name: str = Form(""),
181
+ accepted_privacy: str = Form(""),
182
+ ):
183
+ """The emailed code confirms the email and signs the student in (sign-up, or sign-in before confirming)."""
184
+ ip = client_ip(request)
185
+ email = (email or "").strip().lower()
186
+ rate_limit.check("login-ip", ip, *LIMIT_LOGIN_PER_IP)
187
+ rate_limit.check("login", f"{ip}|{email}", *LIMIT_LOGIN_PER_EMAIL)
188
+ try:
189
+ signin = neon_auth.verify_email(email, (code or "").strip())
190
+ except neon_auth.AuthError as e:
191
+ return _auth_error(e)
192
+ if not signin: # confirmed, but Neon didn't sign in
193
+ return JSONResponse({"confirmed": True, "message": "Email confirmed. Please sign in."})
194
+ try:
195
+ user = user_get_by_id(signin.user.id)
196
+ if not user and _accepted(accepted_privacy):
197
+ _start_account(signin.user, (name or "").strip()[:80] or email.split("@")[0])
198
+ user = user_get_by_id(signin.user.id)
199
+ except Exception:
200
+ neon_auth.sign_out(signin.session)
201
+ return _database_error("Sign-up")
202
+ if not user:
203
+ neon_auth.sign_out(signin.session)
204
+ return _error("No account was finished for this email. Please sign up again with the same email.", 401)
205
+ return _signed_in(signin, user.get("name") or "")
206
+
207
+
208
+ @router.post("/register/send_code")
209
+ def send_sign_up_code(request: Request, email: str = Form(...)):
210
+ """A new code for confirming the email (the last one expired or didn't arrive)."""
211
+ email = (email or "").strip().lower()
212
+ rate_limit.check("forgot-ip", client_ip(request), *LIMIT_FORGOT_PER_IP)
213
+ if _EMAIL_RE.match(email):
214
+ rate_limit.check("signup-code", email, *LIMIT_EMAIL_CODES_PER_USER)
215
+ try:
216
+ neon_auth.send_verification_code(email)
217
+ except neon_auth.AuthError as e:
218
+ if e.status >= 500 or e.status == 429:
219
+ return _auth_error(e)
220
+ return JSONResponse({"message": f"If {email} is waiting to be confirmed, we've emailed it a new code."})
221
 
222
 
223
  @router.post("/login")
 
227
  rate_limit.check("login-ip", ip, *LIMIT_LOGIN_PER_IP)
228
  rate_limit.check("login", f"{ip}|{email}", *LIMIT_LOGIN_PER_EMAIL)
229
  try:
230
+ signin = neon_auth.sign_in(email, password)
231
+ except neon_auth.AuthError as e:
232
+ if e.code != "EMAIL_NOT_VERIFIED":
233
+ return _auth_error(e)
234
+ # Right password, email not confirmed yet: send a code (Neon doesn't on sign-in).
235
+ try:
236
+ _send_code(email)
237
+ except neon_auth.AuthError as e2:
238
+ return _auth_error(e2)
239
+ return _confirm_email(email, 403)
240
+ try:
241
+ user = user_get_by_id(signin.user.id)
242
+ except Exception:
243
+ return _database_error("Sign-in")
244
+ if not user:
245
+ neon_auth.sign_out(signin.session)
246
+ return _error("No account was finished for this email. Please sign up again with the same email.", 401)
247
+ return _signed_in(signin, user.get("name") or "")
248
 
249
 
250
  @router.post("/logout")
251
  def logout(request: Request):
252
+ """End the session at Neon Auth too, so the session id stops working everywhere."""
253
+ neon_auth.sign_out((request.headers.get(SESSION_HEADER) or "").strip())
254
  return JSONResponse({"message": "Signed out."})
255
 
256
 
257
  @router.get("/me")
258
  def get_me(request: Request):
259
+ """Current user info for the session. Requires a valid X-Session-Id."""
260
+ found = signed_in_user((request.headers.get(SESSION_HEADER) or "").strip())
261
+ if not found:
262
  return _error("Not signed in.", 401)
263
+ user = user_get_by_id(found.id)
264
  if not user:
265
  return _error("User not found.", 404)
266
  name = user.get("name") or (user.get("email") or "").split("@")[0]
267
  return JSONResponse({
268
  "name": name or "User",
269
+ "user_id": found.id,
270
  "email": user.get("email") or "",
271
+ "email_verified": found.email_verified,
272
+ "is_admin": found.email_verified and (user.get("email") or "").lower() in settings.ADMIN_EMAILS,
273
+ "preferences": preferences.get(found.id),
274
  })
275
 
276
 
 
307
  user_id: SignedInUser = None,
308
  ):
309
  rate_limit.check("password-check", user_id, *LIMIT_PASSWORD_CHECK_PER_USER)
 
 
310
  problem = _password_problem(new_password)
311
  if problem:
312
  return _error(problem)
313
+ try:
314
+ session = neon_auth.change_password(request.headers.get(SESSION_HEADER) or "", current_password, new_password)
315
+ except neon_auth.AuthError as e:
316
+ return _auth_error(e)
317
+ forget_user(user_id)
318
+ # Every other device is signed out; this one continues with a new session id.
319
+ return JSONResponse({"message": "Password changed. Other devices have been signed out.", "session_id": session})
320
 
321
 
322
  @router.post("/account/delete")
323
  def delete_account(password: str = Form(...), user_id: SignedInUser = None):
324
  """Permanently delete the account and everything stored for it."""
325
  rate_limit.check("password-check", user_id, *LIMIT_PASSWORD_CHECK_PER_USER)
326
+ user = user_get_by_id(user_id)
327
+ try:
328
+ check = neon_auth.sign_in(user["email"], password)
329
+ except neon_auth.AuthError as e:
330
+ if e.code == "INVALID_EMAIL_OR_PASSWORD":
331
+ return _error("Password is incorrect.", 400)
332
+ return _auth_error(e)
333
+ try:
334
+ originals.remove_user(user_id)
335
+ except Exception:
336
+ logger.exception("Couldn't delete the stored originals of %s", user_id)
337
+ delete_all_note_passages(user_id)
338
+ delete_user_vfs(user_id)
339
  study_store.delete_all(user_id)
340
  user_document_delete_many(user_id, path_filter=None)
341
  onenote_token_delete(user_id)
 
342
  chat_cache.clear_user(user_id)
343
  uploads.forget_user_jobs(user_id)
 
344
  usage.delete_user(user_id)
345
  feedback.delete_user(user_id)
346
  preferences.forget(user_id)
 
347
  user_delete(user_id)
348
+ # Sign out every device, then delete the Neon Auth account itself.
349
+ try:
350
+ neon_auth.revoke_sessions(check.session)
351
+ except neon_auth.AuthError:
352
+ logger.warning("Couldn't sign out the devices of a deleted account", exc_info=True)
353
+ neon_auth.delete_user(user_id)
354
+ forget_user(user_id)
355
  return JSONResponse({"message": "Your account and all your notes have been deleted."})
356
 
357
 
358
+ @router.post("/account/verify_email/send")
359
+ def send_email_code(user_id: SignedInUser = None):
360
+ """Email a code that proves the student owns their email address."""
361
+ rate_limit.check("email-code", user_id, *LIMIT_EMAIL_CODES_PER_USER)
362
+ try:
363
+ neon_auth.send_verification_code(user_get_by_id(user_id)["email"])
364
+ except neon_auth.AuthError as e:
365
+ return _auth_error(e)
366
+ return JSONResponse({"message": "We've emailed you a code. It expires in a few minutes."})
367
+
368
+
369
+ @router.post("/account/verify_email")
370
+ def confirm_email_code(code: str = Form(...), user_id: SignedInUser = None):
371
+ rate_limit.check("password-check", user_id, *LIMIT_PASSWORD_CHECK_PER_USER)
372
+ try:
373
+ extra = neon_auth.verify_email(user_get_by_id(user_id)["email"], (code or "").strip())
374
+ except neon_auth.AuthError as e:
375
+ return _auth_error(e)
376
+ if extra:
377
+ neon_auth.sign_out(extra.session) # Neon signs in again on confirming; this device already is
378
+ forget_user(user_id)
379
+ return JSONResponse({"message": "Email confirmed."})
380
+
381
+
382
  FORGOT_MESSAGE = "If an account exists for that email, we've sent a link to reset the password. It expires in 1 hour."
383
 
384
 
385
+ def _reset_redirect() -> str:
386
+ base = FRONTEND_URL
387
+ return base + ("&" if "?" in base else "?") + "reset=1"
388
+
389
+
390
  @router.post("/password/forgot")
391
  def forgot_password(request: Request, email: str = Form(...)):
 
 
392
  email = (email or "").strip().lower()
393
  rate_limit.check("forgot-ip", client_ip(request), *LIMIT_FORGOT_PER_IP)
394
  rate_limit.check("forgot", email, *LIMIT_FORGOT_PER_EMAIL)
395
+ if _EMAIL_RE.match(email):
 
 
 
 
396
  try:
397
+ neon_auth.request_password_reset(email, _reset_redirect())
398
+ except neon_auth.AuthError as e:
399
+ if e.status >= 500:
400
+ return _auth_error(e)
401
  # Same answer either way, so the form can't be used to find out who has an account.
402
  return JSONResponse({"message": FORGOT_MESSAGE})
403
 
 
408
  problem = _password_problem(new_password)
409
  if problem:
410
  return _error(problem)
411
+ try:
412
+ neon_auth.reset_password((token or "").strip(), new_password)
413
+ except neon_auth.AuthError as e:
414
+ return _auth_error(e)
 
415
  return JSONResponse({"message": "Password updated. Please sign in with your new password."})
backend/routes/admin.py CHANGED
@@ -6,7 +6,7 @@ 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
 
@@ -16,10 +16,11 @@ 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:
 
6
  from fastapi.responses import JSONResponse
7
 
8
  from backend import feedback, rate_limit, settings, usage
9
+ from backend.store import user_get_by_id
10
  from backend.deps import SignedInUser
11
  from backend.library import USAGE_ID as LIBRARY_USAGE_ID
12
 
 
16
 
17
 
18
  def is_admin(user_id: str) -> bool:
19
+ """An admin email, confirmed with an emailed code (anyone could sign up with an unconfirmed one)."""
20
  if not settings.ADMIN_EMAILS:
21
  return False
22
  user = user_get_by_id(user_id)
23
+ return bool(user and user["email_verified"] and (user.get("email") or "").lower() in settings.ADMIN_EMAILS)
24
 
25
 
26
  def _require_admin(user_id: str) -> None:
backend/routes/chat.py CHANGED
@@ -1,4 +1,4 @@
1
- """Chat: temporary chat uploads (+ button) and answering questions from notes."""
2
  import json
3
  import logging
4
  from datetime import datetime
@@ -7,11 +7,11 @@ 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,
@@ -27,17 +27,18 @@ router = APIRouter()
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")
@@ -65,9 +66,9 @@ def chat_upload_ephemeral(chat_session_id: str = Form(...), file: UploadFile = F
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,
@@ -102,7 +103,7 @@ def clear_chat_session_cache(chat_session_id: str = Form(...), user_id: SignedIn
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(
@@ -114,8 +115,13 @@ def _prepare_question(
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.")
@@ -131,8 +137,18 @@ def _prepare_question(
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(
@@ -142,12 +158,13 @@ def _prepare_question(
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),
@@ -170,18 +187,21 @@ def query_notes(
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")
@@ -193,6 +213,7 @@ def query_notes_stream(
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
  """
@@ -200,17 +221,19 @@ def query_notes_stream(
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:
@@ -221,8 +244,8 @@ def query_notes_stream(
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")
 
1
+ """Chat: temporary chat uploads (+ button) and answering questions from notes (see backend/pipeline/)."""
2
  import json
3
  import logging
4
  from datetime import datetime
 
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, preferences, rate_limit, uploads, usage
11
  from backend.deps import SignedInUser
 
12
  from backend.paths import file_paths, get_vfs_tree_clean, strip_storage_path
13
+ from backend.pipeline import generation, indexing, models
14
+ from backend.pipeline.retrieval import SearchResult, course_of, find_context
15
  from backend.settings import (
16
  LIMIT_QUESTIONS_PER_DAY,
17
  LIMIT_QUESTIONS_PER_USER,
 
27
  AI_UNAVAILABLE = "The AI couldn't answer right now. Please try again."
28
 
29
 
30
+ MAX_HISTORY_CHARS = 20000
31
+
32
+
33
+ def _parse_history(raw: str) -> list[dict]:
34
+ """Earlier messages of this chat, sent by the app as JSON [{role, content}] (bad input is ignored)."""
35
+ if not (raw or "").strip():
36
+ return []
37
+ try:
38
+ data = json.loads(raw[:MAX_HISTORY_CHARS])
39
+ except json.JSONDecodeError:
40
  return []
41
+ return [m for m in data if isinstance(m, dict)] if isinstance(data, list) else []
 
 
 
 
 
 
42
 
43
 
44
  @router.post("/chat/upload_ephemeral")
 
66
 
67
  truncated = len(text) > MAX_CHAT_UPLOAD_CHARS
68
  text = text[:MAX_CHAT_UPLOAD_CHARS]
69
+ # Fingerprint every passage once now, so questions search the whole file instead of only its start.
70
+ chunks = [c for c, _ in indexing.split_text(text)]
71
+ embeddings = np.asarray(models.embed_passages(chunks), dtype=np.float32)
72
  count = chat_cache.add(
73
  user_id,
74
  sid,
 
103
 
104
  def _ai_failed(err: str) -> None:
105
  logger.warning("Answer generation failed: %s", err)
106
+ alerts.notify("ai-unavailable", f"Language model failed: {err}")
107
 
108
 
109
  def _prepare_question(
 
115
  include_course_context: bool,
116
  chat_session_id: str,
117
  library_path: str = "",
118
+ history: list[dict] | None = None,
119
+ ) -> tuple[str, str, str, list[dict], SearchResult, str]:
120
+ """
121
+ Validate the question and find the note excerpts to answer it from (HTTP errors raise).
122
+ A follow-up ("explain that more simply") is first rewritten to stand on its own, using the
123
+ earlier messages, so the search looks for the right thing.
124
+ """
125
  q = (query or "").strip()
126
  if not q:
127
  raise HTTPException(status_code=400, detail="Query is empty.")
 
137
  ephemeral = chat_cache.items(user_id, chat_session_id)
138
  hl = (highlight or "").strip()
139
  full_q = f'Regarding this selection:\n"""{hl}"""\n\n{q}' if hl else q
140
+ search_q = generation.standalone_question(q, history) if history else q
141
+ usage.record(user_id, **generation.take_usage())
142
  result = find_context(
143
+ user_id,
144
+ f'Regarding this selection:\n"""{hl}"""\n\n{search_q}' if hl else search_q,
145
+ all_paths,
146
+ opened,
147
+ course,
148
+ ephemeral,
149
+ include_course_context,
150
+ library_path=library_path,
151
+ keywords=f"{hl} {search_q}",
152
  )
153
  if not result.selected:
154
  raise HTTPException(
 
158
  else "No notes found to answer from. Upload notes, open a file, or attach one with +.",
159
  )
160
  usage.record(user_id, questions=1)
161
+ return q, full_q, opened, ephemeral, result, search_q
162
 
163
 
164
+ def _answer_metadata(q: str, opened: str, ephemeral: list[dict], result: SearchResult, search_q: str) -> dict:
165
  return {
166
  "query": q,
167
+ "search_query": search_q,
168
  "source_documents": result.source_documents(),
169
  "grounded_on_path": opened,
170
  "ephemeral_files_used": len(ephemeral),
 
187
  include_course_context: bool = Form(True),
188
  chat_session_id: str = Form(""),
189
  library_path: str = Form(""),
190
+ history: str = Form(""),
191
  user_id: SignedInUser = None,
192
  ):
193
+ """Answer a question from the student's notes. `history`: earlier messages of the chat (JSON)."""
194
+ turns = _parse_history(history)
195
+ q, full_q, opened, ephemeral, result, search_q = _prepare_question(
196
+ user_id, query, highlight, opened_file_path, course_path, include_course_context, chat_session_id,
197
+ library_path, turns,
198
  )
199
+ answer, err = generation.answer(full_q, result.context(), history=turns, **preferences.language_kwargs(user_id))
200
+ usage.record(user_id, **generation.take_usage())
 
201
  if err:
202
  _ai_failed(err)
203
  return JSONResponse({"error": AI_UNAVAILABLE, "query": q, "answer": "", "source_documents": []}, status_code=503)
204
+ return JSONResponse({**_answer_metadata(q, opened, ephemeral, result, search_q), "answer": answer or ""})
205
 
206
 
207
  @router.post("/query_folder/stream")
 
213
  include_course_context: bool = Form(True),
214
  chat_session_id: str = Form(""),
215
  library_path: str = Form(""),
216
+ history: str = Form(""),
217
  user_id: SignedInUser = None,
218
  ):
219
  """
 
221
  {"type":"meta",...sources} then {"type":"delta","text":...}* then {"type":"done"} or {"type":"error"}.
222
  `library_path` asks about a shared course PDF (see library.py) instead of an uploaded file.
223
  """
224
+ turns = _parse_history(history)
225
+ q, full_q, opened, ephemeral, result, search_q = _prepare_question(
226
+ user_id, query, highlight, opened_file_path, course_path, include_course_context, chat_session_id,
227
+ library_path, turns,
228
  )
229
  context = result.context()
230
  lang = preferences.language_kwargs(user_id)
231
 
232
  def lines():
233
+ yield json.dumps({"type": "meta", **_answer_metadata(q, opened, ephemeral, result, search_q)}) + "\n"
234
  written: list[str] = []
235
  try:
236
+ for piece in generation.answer_stream(full_q, context, history=turns, **lang):
237
  written.append(piece)
238
  yield json.dumps({"type": "delta", "text": piece}) + "\n"
239
  except Exception as e:
 
244
  # Streaming replies don't report tokens; estimate them for the cost figures.
245
  usage.record(
246
  user_id,
247
+ prompt_tokens=generation.estimate_tokens(full_q + context + json.dumps(turns)),
248
+ completion_tokens=generation.estimate_tokens("".join(written)) if written else 0,
249
  )
250
  if not written:
251
  _ai_failed("empty streamed answer")
backend/routes/files.py CHANGED
@@ -5,21 +5,7 @@ import os
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,
@@ -29,12 +15,6 @@ from backend.file_meta import (
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,
@@ -45,6 +25,15 @@ from backend.paths import (
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,
@@ -53,6 +42,17 @@ from backend.settings import (
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__)
@@ -147,20 +147,20 @@ def get_job(job_id: str, user_id: SignedInUser = None):
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:
@@ -173,11 +173,11 @@ def delete_path(path: str = Form(...), kind: str = Form(...), user_id: SignedInU
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))
@@ -186,7 +186,7 @@ def delete_path(path: str = Form(...), kind: str = Form(...), user_id: SignedInU
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)
@@ -238,20 +238,32 @@ def rename_path(path: str = Form(...), new_name: str = Form(...), user_id: Signe
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)."""
@@ -264,9 +276,9 @@ def save_file_text(path: str = Form(...), text: str = Form(""), user_id: SignedI
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})
@@ -297,7 +309,7 @@ def post_file_meta(
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
 
@@ -306,7 +318,7 @@ def delete_notes(file: str | None = None, files: str | None = None, user_id: Sig
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()]
@@ -314,14 +326,13 @@ def delete_notes(file: str | None = None, files: str | None = None, user_id: Sig
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,
 
5
  from fastapi import APIRouter, File, Form, UploadFile
6
  from fastapi.responses import JSONResponse
7
 
8
+ from backend import originals, rate_limit, uploads, usage
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  from backend.deps import EffectiveUser, SignedInUser
10
  from backend.file_meta import (
11
  delete_key,
 
15
  load_file_meta,
16
  set_entry,
17
  )
 
 
 
 
 
 
18
  from backend.paths import (
19
  file_paths,
20
  get_vfs_tree_clean,
 
25
  valid_name,
26
  vfs_entry_kind,
27
  )
28
+ from backend.pipeline.indexing import (
29
+ delete_all_note_passages,
30
+ delete_note_passages,
31
+ index_note,
32
+ move_folder_notes,
33
+ move_note,
34
+ note_text,
35
+ refresh_note_details,
36
+ )
37
  from backend.settings import (
38
  LIMIT_DELETE_ALL_PER_USER,
39
  LIMIT_TEXT_EDITS_PER_USER,
 
42
  LIMIT_UPLOADS_PER_USER,
43
  MAX_EDITED_TEXT_CHARS,
44
  )
45
+ from backend.store import (
46
+ delete_user_vfs,
47
+ user_document_delete_by_path,
48
+ user_document_delete_many,
49
+ user_document_get,
50
+ user_document_rename_path,
51
+ user_document_upsert,
52
+ user_documents_relocate_prefix,
53
+ user_lock,
54
+ vfs_set_tree,
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__)
 
147
 
148
 
149
  def _relocate_data(user_id: str, tree: list, kind: str, src: str, dest: str) -> None:
150
+ """Move search passages, stored text and metadata from src to dest (file or whole folder)."""
151
  if kind == "file":
152
+ move_note(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
+ move_folder_notes(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 folder tree and the database (with any stored originals)."""
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:
 
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_note_passages(user_id, [path])
177
  user_document_delete_by_path(user_id, path)
178
  delete_key(user_id, path)
179
  else:
180
+ delete_note_passages(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))
 
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 folder tree, with its stored text and passages."""
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)
 
238
 
239
  @router.get("/file_text")
240
  def get_file_text(path: str = "", user_id: SignedInUser = None):
241
+ """The text Study AI 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
+ # Very long files keep only the first part of their text; rebuild the rest from the passages.
249
+ chunk_text = note_text(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.get("/file_original")
256
+ def get_file_original(path: str = "", user_id: SignedInUser = None):
257
+ """A link (valid for a few minutes) to the uploaded PDF or photo itself, for viewing on any device."""
258
+ p = strip_storage_path(path)
259
+ if vfs_entry_kind(get_vfs_tree_clean(user_id), p) != "file":
260
+ return _error("File not found.", 404)
261
+ found = originals.link(user_id, p)
262
+ if not found:
263
+ return _error("The original of this file isn't stored.", 404)
264
+ return found
265
+
266
+
267
  @router.post("/file_text")
268
  def save_file_text(path: str = Form(...), text: str = Form(""), user_id: SignedInUser = None):
269
  """Replace a file's text (e.g. to fix reading mistakes, or to write notes in an empty file)."""
 
276
  return _error("File not found.", 404)
277
  name = os.path.basename(p)
278
  if text.strip():
279
+ chunks = index_note(user_id, p, name, text)["chunks_created"]
280
  else:
281
+ delete_note_passages(user_id, [p])
282
  chunks = 0
283
  user_document_upsert(user_id, p, text, name)
284
  return JSONResponse({"message": "Saved.", "chunks": chunks})
 
309
  doc_type=(doc_type or "other"),
310
  related_paths=rel_list,
311
  )
312
+ n = refresh_note_details(user_id, [path])
313
  return JSONResponse({"path": path, "entry": entry, "chunks_updated": n})
314
 
315
 
 
318
  """
319
  Delete the user's notes.
320
  - No query params: delete all notes, folders and stored text.
321
+ - file=<path> / files=<path1>,<path2>: delete only the search passages for those paths.
322
  """
323
  if file or files:
324
  paths = [p.strip() for p in ([file] if file else files.split(",")) if p and p.strip()]
 
326
  return _error("No paths provided.")
327
  if any(".." in p or p.startswith("/") for p in paths):
328
  return _error("Invalid path.")
329
+ deleted = delete_note_passages(user_id, [strip_storage_path(p) for p in paths])
330
  return JSONResponse({"message": f"Deleted {deleted} chunk(s) for the given file(s).", "deleted_count": deleted})
331
  rate_limit.check("delete-all", user_id, *LIMIT_DELETE_ALL_PER_USER)
332
  with user_lock(user_id):
333
+ deleted_notes = delete_all_note_passages(user_id) > 0
334
+ deleted_vfs = delete_user_vfs(user_id)
335
  user_document_delete_many(user_id, path_filter=None)
 
336
  return JSONResponse({
337
  "message": "All your notes have been deleted.",
338
  "deleted_notes": deleted_notes,
backend/routes/onenote.py CHANGED
@@ -8,7 +8,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,
@@ -66,7 +66,7 @@ def onenote_callback(code: str = "", state: str = "", error: str = "", error_des
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)
 
8
  from fastapi.responses import HTMLResponse, JSONResponse
9
 
10
  from backend import onenote_sync, rate_limit
11
+ from backend.store import (
12
  onenote_oauth_state_create,
13
  onenote_oauth_state_pop_user_id,
14
  onenote_token_get,
 
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 Study AI and choose Sync OneNote from your profile menu.")
70
  except Exception as e:
71
  logger.exception("OneNote token exchange failed")
72
  return _onenote_page("Token exchange failed.", str(e), 500)
backend/routes/study.py CHANGED
@@ -7,24 +7,26 @@ import time
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(
@@ -105,9 +107,9 @@ def _limit_study(user_id: str) -> None:
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
@@ -132,7 +134,7 @@ def study_generate(
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(
@@ -164,7 +166,7 @@ def _summary(
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(
@@ -188,18 +190,6 @@ def study_summary(
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):
@@ -352,7 +342,7 @@ def exam_questions(course_path: str = Form(...), count: int = Form(15), user_id:
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}
 
7
  from fastapi import APIRouter, Form
8
  from fastapi.responses import JSONResponse, Response
9
 
10
+ from backend import alerts, library, preferences, rate_limit, study_store, usage
 
11
  from backend.deps import SignedInUser
12
  from backend.paths import file_paths, get_vfs_tree_clean, strip_storage_path
13
+ from backend.pipeline import generation
14
+ from backend.pipeline.indexing import note_text
15
+ from backend.store import user_document_get
16
  from backend.settings import LIMIT_DECK_CHANGES_PER_USER, LIMIT_STUDY_PER_DAY, LIMIT_STUDY_PER_USER
17
 
18
  router = APIRouter()
19
 
20
 
21
  def _study_text_for_path(user_id: str, rel_path: str) -> str:
22
+ """The file's stored full text; for very long files (stored cut short), the text of its passages."""
23
  p = strip_storage_path(rel_path or "")
24
  if not p:
25
  return ""
26
+ doc = user_document_get(user_id, p)
27
+ if doc and doc["content"].strip() and not doc["truncated"]:
28
+ return doc["content"].strip()
29
+ return (note_text(user_id, p) or (doc or {}).get("content") or "").strip()
30
 
31
 
32
  def _build_study_scope_context(
 
107
 
108
  def _run_study_ai(user_id: str, fn, *args):
109
  """Call a study AI function in the student's language and count its use. Returns (data, err)."""
110
+ generation.take_usage()
111
  data, err = fn(*args, **preferences.language_kwargs(user_id))
112
+ usage.record(user_id, study_requests=1, **generation.take_usage())
113
  if err:
114
  alerts.notify("ai-unavailable", f"Study generation failed: {err}")
115
  return data, err
 
134
  )
135
  if cerr:
136
  return JSONResponse({"error": cerr}, status_code=400)
137
+ data, err = _run_study_ai(user_id, generation.study_items, ctx, task, max(1, min(count, 30)))
138
  if err:
139
  return JSONResponse({"error": err}, status_code=503)
140
  return JSONResponse(
 
166
  )
167
  if cerr:
168
  return JSONResponse({"error": cerr}, status_code=400)
169
+ summary_text, err = _run_study_ai(user_id, generation.summary, ctx)
170
  if err:
171
  return JSONResponse({"error": err}, status_code=503)
172
  return JSONResponse(
 
190
  return _summary(user_id, focus_query, opened_file_path, course_path, include_course_context, library_path)
191
 
192
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  # ---------- Saved decks + spaced repetition ----------
194
  @router.post("/study/decks")
195
  def create_deck(name: str = Form(""), source_path: str = Form(""), cards: str = Form(...), user_id: SignedInUser = None):
 
342
  if not parts:
343
  return JSONResponse({"error": "No text found in that folder's files yet."}, status_code=400)
344
  ctx = f"Mock exam for the course folder: {course}\n\n" + "\n\n".join(parts)
345
+ data, err = _run_study_ai(user_id, generation.study_items, ctx, "mcq", max(5, min(count, 30)))
346
  if err:
347
  return JSONResponse({"error": err}, status_code=503)
348
  return {"items": data, "course": course, "files_used": used}
backend/search.py DELETED
@@ -1,229 +0,0 @@
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 (Interview.ai'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
- OPEN_PDF_KEEP = 3 # passages of the open PDF always sent when it is nearly as relevant...
30
- OPEN_PDF_KEEP_GAP = 0.25 # ...as the best passage of its course (within this much)
31
-
32
-
33
- @dataclass
34
- class SearchResult:
35
- stage: str = ""
36
- selected: list[dict] = field(default_factory=list)
37
- best_scores: dict[str, float] = field(default_factory=dict)
38
-
39
- def context(self) -> str:
40
- parts = []
41
- for d in self.selected:
42
- content = (d.get("content") or "").strip()
43
- if not content:
44
- continue
45
- md = d.get("metadata") or {}
46
- label = md.get("path") or "chunk"
47
- if md.get("library"):
48
- label = f"Course notes: {md.get('label') or label}"
49
- # Most course PDFs are one long page: a page number would only add noise there.
50
- if md.get("page") and int(md.get("pages") or 2) > 1:
51
- label += f", page {md['page']}"
52
- if md.get("is_primary_authority"):
53
- label += " (main source)"
54
- parts.append(f"[{label}]\n{content[:1200]}")
55
- return "\n\n".join(parts)
56
-
57
- def source_documents(self) -> list[dict]:
58
- return [{k: v for k, v in d.items() if k != "_score"} for d in self.selected]
59
-
60
-
61
- def _search_chunks(
62
- col, space: str, q_emb: list[float], where: dict | None, allowed: set[str], n_results: int
63
- ) -> list[dict]:
64
- """
65
- Best stored chunks matching `where` (None = whole collection), kept only if their file is still
66
- in the folder tree (`allowed`), scored as cosine similarity with a small boost for main-source files.
67
- """
68
- res = col.query(
69
- query_embeddings=[q_emb],
70
- n_results=n_results,
71
- include=["documents", "metadatas", "distances"],
72
- **({"where": where} if where else {}),
73
- )
74
- ids = (res.get("ids") or [[]])[0] or []
75
- docs = (res.get("documents") or [[]])[0] or []
76
- metas = (res.get("metadatas") or [[]])[0] or []
77
- dists = (res.get("distances") or [[]])[0] or []
78
- out = []
79
- for i, cid in enumerate(ids):
80
- content = (docs[i] if i < len(docs) else "") or ""
81
- md = metas[i] if i < len(metas) and isinstance(metas[i], dict) else {}
82
- if not content.strip() or md.get("path") not in allowed:
83
- continue
84
- dist = float(dists[i]) if i < len(dists) and dists[i] is not None else 2.0
85
- score = distance_to_similarity(dist, space)
86
- if md.get("is_primary_authority"):
87
- score += MAIN_SOURCE_BOOST
88
- out.append({"id": cid, "content": content, "metadata": md, "_score": score})
89
- out.sort(key=lambda d: d["_score"], reverse=True)
90
- return out
91
-
92
-
93
- def _search_chat_uploads(ephemeral: list[dict], q_vec: np.ndarray) -> list[dict]:
94
- """Top 3 chunks per chat-uploaded file, scored as cosine similarity."""
95
- out: list[dict] = []
96
- for i, it in enumerate(ephemeral):
97
- chunks = it.get("chunks") or []
98
- embs = it.get("embeddings")
99
- if not chunks or embs is None or len(embs) != len(chunks):
100
- continue
101
- scores = embs @ q_vec
102
- for j, idx in enumerate(np.argsort(-scores)[:3]):
103
- out.append({
104
- "id": f"ephemeral|{i}|{j}",
105
- "content": chunks[int(idx)],
106
- "metadata": {
107
- "path": f"[chat-upload] {it.get('name') or 'file'}",
108
- "source_file": it.get("name") or "chat-upload",
109
- "ephemeral_chat_upload": 1,
110
- },
111
- "_score": float(scores[int(idx)]),
112
- })
113
- out.sort(key=lambda d: d["_score"], reverse=True)
114
- return out
115
-
116
-
117
- def _closest(docs: list[dict]) -> list[dict]:
118
- """The best excerpts of a stage: those scoring close to its top match, at most MAX_SELECTED."""
119
- if not docs:
120
- return []
121
- floor = docs[0]["_score"] - SOURCE_SCORE_WINDOW
122
- return [d for d in docs if d["_score"] >= floor][:MAX_SELECTED]
123
-
124
-
125
- def course_of(opened: str, course_path: str) -> str:
126
- course = course_path or ""
127
- if not course and opened:
128
- course = opened.split("/", 1)[0] if "/" in opened else opened
129
- return course.split("/", 1)[0] if course else ""
130
-
131
-
132
- def find_context(
133
- user_id: str,
134
- question: str,
135
- all_paths: list[str],
136
- opened: str,
137
- course: str,
138
- ephemeral: list[dict],
139
- include_other_notes: bool = True,
140
- library_path: str = "",
141
- ) -> SearchResult:
142
- col = get_user_collection(user_id)
143
- space = collection_distance_space(col)
144
- q_vec = np.asarray(embed_texts([question])[0], dtype=np.float32)
145
- q_emb = q_vec.tolist()
146
- all_set = set(all_paths)
147
-
148
- eph_docs = _search_chat_uploads(ephemeral, q_vec)
149
- open_docs = _search_chunks(col, space, q_emb, {"path": opened}, all_set, 6) if opened in all_set else []
150
-
151
- # Shared course library: the open course PDF and the other PDFs of the same course, ranked
152
- # together with a small lead for the open PDF, so a lecture that clearly answers the question
153
- # wins over a loosely related open PDF (course notes on one subject all score fairly high).
154
- lib_file_docs: list[dict] = []
155
- lib_subject_docs: list[dict] = []
156
- lib_file, lib_subject = library.scope_of(library_path)
157
- if lib_file:
158
- lib_file_docs = library.search(q_emb, {"path": lib_file}, 6)
159
- if lib_subject and (include_other_notes or not lib_file):
160
- subject_where = {"subject": lib_subject}
161
- if lib_file:
162
- subject_where = {"$and": [subject_where, {"path": {"$ne": lib_file}}]}
163
- lib_subject_docs = library.search(q_emb, subject_where, 24)[:MAX_SELECTED]
164
- lib_docs = sorted(
165
- [{**d, "_score": d["_score"] + OPEN_LIBRARY_FILE_LEAD} for d in lib_file_docs] + lib_subject_docs,
166
- key=lambda d: d["_score"],
167
- reverse=True,
168
- )
169
- from_open_pdf = bool(lib_docs) and lib_docs[0]["metadata"].get("path") == lib_file
170
- lib_stage = "library_file" if from_open_pdf else "library_subject"
171
- lib_min = MIN_SCORE_LIBRARY_FILE if from_open_pdf else MIN_SCORE_LIBRARY_SUBJECT
172
-
173
- # Course and "everything else" are selected with metadata filters (few predicates, no huge
174
- # path lists), then checked against the tree so deleted files never show up.
175
- course_docs: list[dict] = []
176
- other_docs: list[dict] = []
177
- if include_other_notes and all_paths:
178
- not_opened = {"path": {"$ne": opened}} if opened else None
179
- if course:
180
- course_where = {"$and": [{"course_id": course}, not_opened]} if not_opened else {"course_id": course}
181
- course_docs = _search_chunks(col, space, q_emb, course_where, all_set, 24)[:MAX_SELECTED]
182
- other_where = {"course_id": {"$ne": course}}
183
- else:
184
- other_where = not_opened
185
- other_docs = _search_chunks(col, space, q_emb, other_where, all_set, 24)[:MAX_SELECTED]
186
-
187
- stages = [
188
- ("ephemeral", eph_docs, MIN_SCORE_CHAT_UPLOAD),
189
- (lib_stage, lib_docs, lib_min),
190
- ("opened", open_docs, MIN_SCORE_OPEN_FILE),
191
- ("course", course_docs, MIN_SCORE_COURSE),
192
- ("all_notes", other_docs, MIN_SCORE_ALL_NOTES),
193
- ]
194
- scored = [*stages, ("library_file", lib_file_docs, 0), ("library_subject", lib_subject_docs, 0)]
195
- result = SearchResult(
196
- best_scores={name: (round(docs[0]["_score"], 4) if docs else -1.0) for name, docs, _ in scored}
197
- )
198
- # Use the highest-priority stage that is relevant enough; otherwise the best-scoring one.
199
- for name, docs, min_score in stages:
200
- if docs and docs[0]["_score"] >= min_score:
201
- result.stage, result.selected = name, _closest(docs)
202
- _keep_open_pdf(result, lib_file_docs, lib_subject_docs)
203
- return result
204
- # A question about a course PDF never falls back to loosely related notes of the student's own
205
- # (e.g. sample physics notes for a maths course): only the course library itself.
206
- fallback = [(lib_stage, lib_docs, lib_min)] if lib_subject else stages
207
- available = [(name, docs) for name, docs, _ in fallback if docs]
208
- if available:
209
- result.stage, docs = max(available, key=lambda s: s[1][0]["_score"])
210
- result.selected = _closest(docs)
211
- _keep_open_pdf(result, lib_file_docs, lib_subject_docs)
212
- return result
213
-
214
-
215
- def _keep_open_pdf(result: SearchResult, file_docs: list[dict], subject_docs: list[dict]) -> None:
216
- """
217
- The student asked while reading a course PDF: make sure its best passages reach the answer when
218
- it is nearly as relevant as the rest of the course, even if many other passages score a little
219
- higher (e.g. exam answers that all mention "time complexity"). They go first in the context.
220
- """
221
- if not file_docs or not result.stage.startswith("library"):
222
- return
223
- best_other = subject_docs[0]["_score"] if subject_docs else -1.0
224
- if file_docs[0]["_score"] < max(MIN_SCORE_LIBRARY_FILE, best_other - OPEN_PDF_KEEP_GAP):
225
- return
226
- keep = [d for d in file_docs[:OPEN_PDF_KEEP] if d["_score"] >= MIN_SCORE_LIBRARY_FILE]
227
- kept_ids = {d["id"] for d in keep}
228
- result.selected = (keep + [d for d in result.selected if d["id"] not in kept_ids])[:MAX_SELECTED]
229
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/settings.py CHANGED
@@ -1,4 +1,5 @@
1
  """Settings read from the environment, plus request limits and thresholds in one place."""
 
2
  import os
3
 
4
 
@@ -13,6 +14,18 @@ def _env_float(name: str, default: float) -> float:
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
@@ -20,14 +33,65 @@ 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.
@@ -61,14 +125,16 @@ 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
 
@@ -81,13 +147,9 @@ def allowed_origins() -> list[str]:
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 Interview.ai's Notes tab: a public Supabase Storage bucket. The key is that project's
90
- # publishable anon key, already served in plain text by Interview.ai (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("/")
@@ -107,14 +169,14 @@ 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
 
 
1
  """Settings read from the environment, plus request limits and thresholds in one place."""
2
+ import json
3
  import os
4
 
5
 
 
14
  return default
15
 
16
 
17
+ def _env_bool(name: str, default: bool) -> bool:
18
+ return _env_str(name, "true" if default else "false").lower() in ("1", "true", "yes", "on")
19
+
20
+
21
+ def _env_json(name: str, default: dict) -> dict:
22
+ try:
23
+ value = json.loads(os.getenv(name) or "null")
24
+ except ValueError:
25
+ return default
26
+ return value if isinstance(value, dict) else default
27
+
28
+
29
  MAX_UPLOAD_MB = _env_float("MAX_UPLOAD_MB", 20)
30
  MAX_UPLOAD_BYTES = int(MAX_UPLOAD_MB * 1024 * 1024)
31
  MAX_ACTIVE_UPLOADS_PER_USER = 10 # queued + processing; each holds the file in memory until done
 
33
  MAX_CHAT_UPLOAD_CHARS = int(_env_float("MAX_CHAT_UPLOAD_CHARS", 300000))
34
  MAX_CHAT_FILES_PER_SESSION = 10
35
  MAX_EDITED_TEXT_CHARS = 500000
36
+ USER_DOCUMENT_MAX_BYTES = int(_env_float("USER_DOCUMENT_MAX_BYTES", 2000000)) # stored text per file
37
+
38
+ # ---------- Database ----------
39
+ # One Postgres database (with the pgvector extension) holds everything: accounts, folders, decks,
40
+ # usage, and the note passages with their search fingerprints. Neon and Supabase both work.
41
+ DATABASE_URL = (os.getenv("DATABASE_URL") or "").strip()
42
+
43
+ # ---------- Sign-in (Neon Auth, see backend/neon_auth.py) ----------
44
+ # Accounts, passwords, password-reset and email-check emails are handled by Neon Auth. Its address is
45
+ # in the Neon Console under Auth -> Configuration, e.g. https://ep-....neonauth.<region>.aws.neon.tech/neondb/auth
46
+ NEON_AUTH_BASE_URL = (os.getenv("NEON_AUTH_BASE_URL") or "").strip().rstrip("/")
47
+ AUTH_CACHE_SECONDS = _env_float("AUTH_CACHE_SECONDS", 60) # how long a checked sign-in is trusted
48
+
49
+ # ---------- Students' original files (PDFs and photos) ----------
50
+ # Kept in an S3-compatible bucket (Neon Object Storage) so they open on any device. Without these
51
+ # settings only the text read from each file is kept. The course library's PDFs stay in Supabase.
52
+ FILES_S3_ENDPOINT = (os.getenv("AWS_ENDPOINT_URL_S3") or "").strip()
53
+ FILES_S3_BUCKET = (os.getenv("S3_BUCKET") or "").strip()
54
+ FILES_S3_REGION = _env_str("AWS_REGION", "us-east-1")
55
+ MAX_STORED_FILES_MB_PER_USER = _env_float("MAX_STORED_FILES_MB_PER_USER", 200)
56
+ MAX_STORED_FILES_MB_TOTAL = _env_float("MAX_STORED_FILES_MB_TOTAL", 4500) # Neon's free plan: 5 GB
57
+
58
+ # ---------- AI models (see backend/pipeline/models.py) ----------
59
+ # Search model: turns passages and questions into "meaning fingerprints". Multilingual, so a question
60
+ # in Hindi finds notes in English and the other way round. Changing it means re-indexing all notes.
61
+ EMBED_MODEL = _env_str("EMBED_MODEL", "intfloat/multilingual-e5-small")
62
+ EMBED_DIM = int(_env_float("EMBED_DIM", 384))
63
+ # Re-checking model: reads the question and each candidate passage together and scores how well the
64
+ # passage answers it (0..1). "" turns it off (search then ranks by the fingerprints alone).
65
+ RERANK_MODEL = (os.getenv("RERANK_MODEL") if os.getenv("RERANK_MODEL") is not None
66
+ else "cross-encoder/mmarco-mMiniLMv2-L12-H384-v1").strip()
67
+ # Language model: "sarvam" (default) or "openai_like" (any service with an OpenAI-style chat API,
68
+ # set LLM_API_BASE, LLM_API_KEY and LLM_MODEL). Sarvam Vision still reads PDFs and photos either way.
69
+ LLM_PROVIDER = _env_str("LLM_PROVIDER", "sarvam").lower()
70
+ LLM_API_BASE = (os.getenv("LLM_API_BASE") or "").strip()
71
+ LLM_API_KEY = (os.getenv("LLM_API_KEY") or "").strip()
72
+ LLM_MODEL = (os.getenv("LLM_MODEL") or "").strip()
73
+ # With openai_like: extra request fields that switch the model's thinking off. Quick jobs (rewriting
74
+ # follow-up questions, flashcards, quizzes, summaries) always run without thinking. The default suits
75
+ # DeepSeek and Qwen on NVIDIA, DeepInfra and Together; OpenRouter uses {"reasoning": {"enabled": false}}.
76
+ LLM_THINKING_OFF = _env_json("LLM_THINKING_OFF", {"chat_template_kwargs": {"thinking": False}})
77
+ # Whether the model thinks before answering questions: first words come later, hard questions can
78
+ # get better answers. Off = answers start straight away.
79
+ ANSWER_THINKING = _env_bool("ANSWER_THINKING", True)
80
+
81
+ # Passages: notes are cut into pieces of about this many characters, overlapping a little.
82
+ CHUNK_CHARS = 750
83
+ CHUNK_OVERLAP_CHARS = 100
84
+
85
+ # Relevance (0..1, from the re-checking model) a source needs to count as answering the question.
86
+ MIN_SCORE_CHAT_UPLOAD = 0.15
87
+ MIN_SCORE_OPEN_FILE = 0.10
88
+ MIN_SCORE_COURSE = 0.15
89
+ MIN_SCORE_ALL_NOTES = 0.15
90
  MAIN_SOURCE_BOOST = 0.03 # small ranking boost for files the student marked as their main source
91
+ SOURCE_SCORE_WINDOW = 0.6 # keep excerpts scoring within this much of the best one...
92
+ MIN_KEEP_SCORE = 0.05 # ...and at least this relevant (unless nothing is: then the best few)
93
+ CANDIDATES_PER_SEARCH = 8 # passages taken by meaning and (separately) by keywords, per place searched
94
+ HISTORY_TURNS = 6 # earlier chat messages used to understand a follow-up question
95
 
96
  # Request limits as (max requests, window seconds). Per-IP limits are generous because a whole
97
  # campus can share one public IP; the per-email login limit is what stops password guessing.
 
125
  LIMIT_STUDY_PER_DAY = (100, 86400)
126
 
127
  MIN_PASSWORD_LEN = 8
128
+ MAX_PASSWORD_LEN = 128 # Neon Auth's limit
129
 
130
+ # The website (Interview.ai). Password-reset and reminder emails link here; Neon Auth trusts its origin.
131
+ FRONTEND_URL = _env_str("FRONTEND_URL", "https://cherie-dips.github.io/SDE-Prep/")
132
 
133
  DEFAULT_CORS_ORIGINS = (
134
+ "http://localhost:8001", # the site on your computer (python3 -m http.server 8001 -d site)
135
+ "http://127.0.0.1:8001",
136
+ "http://localhost:5173", # Study AI alone (npm run dev in study-ai/)
137
  "http://127.0.0.1:5173",
 
138
  "https://cherie-dips.github.io",
139
  )
140
 
 
147
  return [o.strip().rstrip("/") for o in raw.split(",") if o.strip()]
148
 
149
 
 
 
 
 
150
  # ---------- Shared course library (read once on the server, searched by every student) ----------
151
  # The PDFs behind Interview.ai's Notes tab: a public Supabase Storage bucket. The key is that project's
152
+ # publishable anon key, already served in plain text by Interview.ai (site/js/notes-data.js); it can only
153
  # read the bucket. Never put a service_role key here.
154
  LIBRARY_ENABLED = _env_bool("LIBRARY_ENABLED", True)
155
  LIBRARY_SUPABASE_URL = _env_str("LIBRARY_SUPABASE_URL", "https://jlmzxsaysnvoxbutfkxw.supabase.co").rstrip("/")
 
169
  # Check the bucket for new or changed PDFs every N hours. 0 = only when started by hand
170
  # (scripts/index_library.py or the admin endpoint), because reading pages with Sarvam costs money.
171
  LIBRARY_SYNC_HOURS = _env_float("LIBRARY_SYNC_HOURS", 0)
172
+ MIN_SCORE_LIBRARY_FILE = 0.10 # the course PDF the student has open (same bar as an open file)
173
+ MIN_SCORE_LIBRARY_SUBJECT = 0.15 # the other PDFs of that course
174
 
175
 
176
  # ---------- Running a pilot ----------
177
  APP_TIMEZONE = _env_str("APP_TIMEZONE", "Asia/Kolkata") # "today", streaks and reminder times use this
178
  STARTER_NOTES = _env_bool("STARTER_NOTES", True) # new accounts get a "Getting started" folder
179
+ PRIVACY_VERSION = "2026-10-14" # bump when the privacy note changes
180
  ADMIN_EMAILS = {e.strip().lower() for e in (os.getenv("ADMIN_EMAILS") or "").split(",") if e.strip()}
181
  ALERT_WEBHOOK_URL = (os.getenv("ALERT_WEBHOOK_URL") or "").strip() # Slack/Discord-style webhook for errors
182
 
backend/starter_notes.py CHANGED
@@ -6,9 +6,9 @@ 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
@@ -51,33 +51,22 @@ 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 Interview.ai'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()
 
6
 
7
  STARTER_FOLDER = "Getting started"
8
 
9
+ WELCOME = """# Welcome to Study AI
10
 
11
+ Study AI 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
 
51
  """
52
 
53
  STARTER_FILES = (
54
+ ("Welcome to Study AI.md", WELCOME),
55
  ("Sample - Newton's laws of motion.md", SAMPLE_PHYSICS),
56
  )
57
 
58
+ def add_starter_notes(user_id: str) -> None:
 
 
 
 
 
 
 
 
 
 
 
59
  """Save the starter files for a new account (no AI calls; only local embeddings)."""
60
  from backend.uploads import save_note_text
61
 
62
+ for name, text in STARTER_FILES:
63
  try:
64
  save_note_text(user_id, STARTER_FOLDER, name, text)
65
  except Exception:
66
  logger.exception("Could not add starter note %s for %s", name, user_id)
67
 
68
 
69
+ def add_starter_notes_in_background(user_id: str) -> None:
70
  threading.Thread(
71
+ target=add_starter_notes, args=(user_id,), name="starter-notes", daemon=True
72
  ).start()
backend/store.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Account details, folders, file text and OneNote tokens in Postgres (tables in db.SCHEMA).
3
+
4
+ The function names match the older ChromaDB version, so routes didn't need to change. Note passages
5
+ (the searchable pieces of each file) are in backend/pipeline/indexing.py.
6
+ """
7
+ import json
8
+ import logging
9
+ import os
10
+ import threading
11
+ import time
12
+
13
+ from backend import db, originals, settings
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ _user_locks: dict[str, threading.RLock] = {}
18
+ _user_locks_guard = threading.Lock()
19
+
20
+
21
+ def user_lock(user_id: str) -> threading.RLock:
22
+ """Per-user lock so two requests can't overwrite each other's folder tree or file metadata."""
23
+ with _user_locks_guard:
24
+ lock = _user_locks.get(user_id)
25
+ if lock is None:
26
+ lock = _user_locks[user_id] = threading.RLock()
27
+ return lock
28
+
29
+
30
+ def clean_text(text: str) -> str:
31
+ """Postgres text can't hold NUL characters (some PDFs contain them)."""
32
+ return (text or "").replace("\x00", "")
33
+
34
+
35
+ def _under(param: str) -> str:
36
+ """SQL condition: `path` is the folder in :param or inside it (no LIKE: names may contain % or _)."""
37
+ return f"(path = :{param} OR left(path, length(:{param}) + 1) = :{param} || '/')"
38
+
39
+
40
+ # ---------- Users ----------
41
+ # Accounts and passwords are in Neon Auth (backend/neon_auth.py); this table keeps Study AI's own
42
+ # details per account (preferences, privacy acceptance), under the Neon Auth user id.
43
+ def _user(row: dict | None) -> dict | None:
44
+ if not row:
45
+ return None
46
+ meta = {"email": row["email"], "name": row["name"], "created_at": int(row["created_at"]), **(row["meta"] or {})}
47
+ return {
48
+ "user_id": row["id"],
49
+ "email": row["email"],
50
+ "name": row["name"],
51
+ "email_verified": bool(row["email_verified"]),
52
+ "meta": meta,
53
+ }
54
+
55
+
56
+ def user_create(user_id: str, email: str, name: str, email_verified: bool = False, **extra) -> bool:
57
+ """Add a user (no-op if the id exists already). Returns True if it was added."""
58
+ return db.execute(
59
+ "INSERT INTO users (id, email, name, email_verified, created_at, meta) "
60
+ "VALUES (:id, :email, :name, :verified, :now, CAST(:meta AS jsonb)) ON CONFLICT (id) DO NOTHING",
61
+ id=user_id,
62
+ email=email.lower(),
63
+ name=name or email.split("@")[0],
64
+ verified=bool(email_verified),
65
+ now=int(time.time()),
66
+ meta=json.dumps(extra),
67
+ ) > 0
68
+
69
+
70
+ def user_sync(user_id: str, email: str, name: str, email_verified: bool) -> bool:
71
+ """Copy the email, name and email check from Neon Auth. False if the user isn't in this table."""
72
+ row = db.one(
73
+ "UPDATE users SET email = :email, name = CASE WHEN :name = '' THEN name ELSE :name END, "
74
+ "email_verified = :verified WHERE id = :id RETURNING id",
75
+ id=user_id,
76
+ email=email.lower(),
77
+ name=name,
78
+ verified=bool(email_verified),
79
+ )
80
+ return row is not None
81
+
82
+
83
+ def user_get_by_id(user_id: str) -> dict | None:
84
+ """User record, or None if it doesn't exist. Database errors raise."""
85
+ return _user(db.one("SELECT * FROM users WHERE id = :id", id=user_id))
86
+
87
+
88
+ def user_update_metadata(user_id: str, **fields) -> dict:
89
+ """Set some metadata fields on a user record (other fields are kept). Returns the new metadata."""
90
+ row = db.one(
91
+ "UPDATE users SET meta = meta || CAST(:fields AS jsonb) WHERE id = :id RETURNING *",
92
+ id=user_id,
93
+ fields=json.dumps(fields),
94
+ )
95
+ if not row:
96
+ raise ValueError("User not found")
97
+ return _user(row)["meta"]
98
+
99
+
100
+ def users_where(where: dict) -> list[dict]:
101
+ """Users whose metadata contains these values, e.g. {"pref_reminders": 1}."""
102
+ found = db.rows("SELECT * FROM users WHERE meta @> CAST(:w AS jsonb) ORDER BY created_at", w=json.dumps(where))
103
+ return [_user(r) for r in found]
104
+
105
+
106
+ def user_delete(user_id: str) -> None:
107
+ db.execute("DELETE FROM users WHERE id = :id", id=user_id)
108
+
109
+
110
+ # ---------- File text (the full text read from each file) ----------
111
+ def _truncate_utf8_bytes(text: str, max_bytes: int) -> tuple[str, int]:
112
+ raw = (text or "").encode("utf-8")
113
+ if len(raw) <= max_bytes:
114
+ return (text or ""), len(raw)
115
+ return raw[: max(0, max_bytes)].decode("utf-8", errors="ignore"), len(raw)
116
+
117
+
118
+ def _drop_originals(removed: list[dict]) -> None:
119
+ """Delete the stored originals of document rows that were just deleted."""
120
+ originals.remove([r["original_key"] for r in removed if r.get("original_key")])
121
+
122
+
123
+ def user_document_upsert(user_id: str, path: str, content: str, original_filename: str):
124
+ """Store extracted text for a path (an edit keeps the file's stored original, see originals.py)."""
125
+ trimmed, full_bytes = _truncate_utf8_bytes(clean_text(content), settings.USER_DOCUMENT_MAX_BYTES)
126
+ db.execute(
127
+ "INSERT INTO documents (user_id, path, original_filename, content, truncated, updated_at) "
128
+ "VALUES (:u, :p, :name, :content, :trunc, :now) "
129
+ "ON CONFLICT (user_id, path) DO UPDATE SET original_filename = EXCLUDED.original_filename, "
130
+ "content = EXCLUDED.content, truncated = EXCLUDED.truncated, updated_at = EXCLUDED.updated_at",
131
+ u=str(user_id),
132
+ p=str(path or ""),
133
+ name=str(original_filename or ""),
134
+ content=trimmed,
135
+ trunc=len(trimmed.encode("utf-8")) < full_bytes,
136
+ now=int(time.time()),
137
+ )
138
+
139
+
140
+ def user_document_get(user_id: str, path: str) -> dict | None:
141
+ """{"content", "truncated", "original_filename"} for a path, or None if nothing is stored."""
142
+ row = db.one(
143
+ "SELECT content, truncated, original_filename FROM documents WHERE user_id = :u AND path = :p",
144
+ u=str(user_id),
145
+ p=str(path),
146
+ )
147
+ return dict(row) if row else None
148
+
149
+
150
+ def user_document_get_content(user_id: str, path: str) -> str | None:
151
+ doc = user_document_get(user_id, path)
152
+ return doc["content"] if doc else None
153
+
154
+
155
+ def user_document_delete_by_path(user_id: str, path: str):
156
+ _drop_originals(db.rows(
157
+ "DELETE FROM documents WHERE user_id = :u AND path = :p RETURNING original_key", u=str(user_id), p=str(path)
158
+ ))
159
+
160
+
161
+ def user_document_delete_many(user_id: str, path_filter=None):
162
+ """Delete documents for user_id. path_filter: if callable(path) -> bool, only delete matching paths."""
163
+ if path_filter is None:
164
+ _drop_originals(db.rows("DELETE FROM documents WHERE user_id = :u RETURNING original_key", u=str(user_id)))
165
+ return
166
+ paths = [r["path"] for r in db.rows("SELECT path FROM documents WHERE user_id = :u", u=str(user_id))]
167
+ doomed = [p for p in paths if path_filter(p)]
168
+ if doomed:
169
+ _drop_originals(db.rows(
170
+ "DELETE FROM documents WHERE user_id = :u AND path = ANY(:paths) RETURNING original_key",
171
+ u=str(user_id),
172
+ paths=doomed,
173
+ ))
174
+
175
+
176
+ def user_documents_relocate_prefix(user_id: str, old_prefix: str, new_prefix: str) -> int:
177
+ """Rename stored document paths under old_prefix to new_prefix (a folder move or rename)."""
178
+ with db.transaction() as conn:
179
+ # Anything already stored at the destination is left over from deleted files: replace it.
180
+ removed = db.rows(
181
+ f"DELETE FROM documents WHERE user_id = :u AND {_under('new')} AND NOT {_under('old')} RETURNING original_key",
182
+ conn,
183
+ u=str(user_id),
184
+ old=old_prefix,
185
+ new=new_prefix,
186
+ )
187
+ moved = db.execute(
188
+ f"UPDATE documents SET path = :new || substr(path, length(:old) + 1) WHERE user_id = :u AND {_under('old')}",
189
+ conn,
190
+ u=str(user_id),
191
+ old=old_prefix,
192
+ new=new_prefix,
193
+ )
194
+ _drop_originals(removed)
195
+ return moved
196
+
197
+
198
+ def user_document_rename_path(user_id: str, old_path: str, new_path: str) -> bool:
199
+ """Move stored extracted text from old_path to new_path."""
200
+ with db.transaction() as conn:
201
+ if not db.one("SELECT 1 AS ok FROM documents WHERE user_id = :u AND path = :p", conn, u=user_id, p=old_path):
202
+ return False
203
+ removed = db.rows(
204
+ "DELETE FROM documents WHERE user_id = :u AND path = :p RETURNING original_key", conn, u=user_id, p=new_path
205
+ )
206
+ db.execute(
207
+ "UPDATE documents SET path = :new, original_filename = CASE WHEN original_filename = '' "
208
+ "THEN :name ELSE original_filename END WHERE user_id = :u AND path = :old",
209
+ conn,
210
+ u=user_id,
211
+ old=old_path,
212
+ new=new_path,
213
+ name=os.path.basename(new_path.replace("\\", "/")),
214
+ )
215
+ _drop_originals(removed)
216
+ return True
217
+
218
+
219
+ # ---------- Folder tree + file metadata ----------
220
+ def _folders_value(user_id: str, column: str, default):
221
+ raw = db.scalar(f"SELECT {column} FROM folders WHERE user_id = :u", u=user_id)
222
+ return raw if isinstance(raw, type(default)) else default
223
+
224
+
225
+ def _folders_set(user_id: str, column: str, value) -> None:
226
+ db.execute(
227
+ f"INSERT INTO folders (user_id, {column}) VALUES (:u, CAST(:v AS jsonb)) "
228
+ f"ON CONFLICT (user_id) DO UPDATE SET {column} = EXCLUDED.{column}",
229
+ u=user_id,
230
+ v=json.dumps(value, ensure_ascii=False),
231
+ )
232
+
233
+
234
+ def vfs_get_tree(user_id: str) -> list:
235
+ """The user's folder tree ([] if none yet). Database errors raise, so a failed read is never
236
+ mistaken for an empty tree (which a caller might then save over the real one)."""
237
+ return _folders_value(user_id, "tree", [])
238
+
239
+
240
+ def vfs_set_tree(user_id: str, tree: list) -> None:
241
+ _folders_set(user_id, "tree", tree)
242
+
243
+
244
+ def vfs_get_file_meta_dict(user_id: str) -> dict:
245
+ return _folders_value(user_id, "file_meta", {})
246
+
247
+
248
+ def vfs_set_file_meta_dict(user_id: str, meta: dict) -> None:
249
+ _folders_set(user_id, "file_meta", meta)
250
+
251
+
252
+
253
+ def delete_user_vfs(user_id: str) -> bool:
254
+ """Remove the folder tree and file details. True if there were any."""
255
+ return db.execute("DELETE FROM folders WHERE user_id = :u", u=user_id) > 0
256
+
257
+
258
+ # ---------- OneNote sign-in ----------
259
+ def onenote_oauth_state_create(user_id: str, state: str, expires_at_epoch: int) -> None:
260
+ db.execute(
261
+ "INSERT INTO onenote_oauth_states (state, user_id, expires_at) VALUES (:s, :u, :exp) "
262
+ "ON CONFLICT (state) DO UPDATE SET user_id = EXCLUDED.user_id, expires_at = EXCLUDED.expires_at",
263
+ s=state,
264
+ u=str(user_id),
265
+ exp=int(expires_at_epoch),
266
+ )
267
+
268
+
269
+ def onenote_oauth_state_pop_user_id(state: str) -> str | None:
270
+ try:
271
+ row = db.one("DELETE FROM onenote_oauth_states WHERE state = :s RETURNING user_id, expires_at", s=state)
272
+ except Exception:
273
+ logger.warning("OneNote OAuth state lookup failed", exc_info=True)
274
+ return None
275
+ if not row or not row["user_id"]:
276
+ return None
277
+ if row["expires_at"] and int(row["expires_at"]) < int(time.time()):
278
+ return None
279
+ return row["user_id"]
280
+
281
+
282
+ def onenote_token_upsert(user_id: str, token_payload: dict) -> None:
283
+ payload = token_payload if isinstance(token_payload, dict) else {}
284
+ try:
285
+ expires_at = int(payload.get("expires_at") or 0)
286
+ except (TypeError, ValueError):
287
+ expires_at = 0
288
+ db.execute(
289
+ "INSERT INTO onenote_tokens (user_id, token, expires_at) VALUES (:u, CAST(:t AS jsonb), :exp) "
290
+ "ON CONFLICT (user_id) DO UPDATE SET token = EXCLUDED.token, expires_at = EXCLUDED.expires_at",
291
+ u=str(user_id),
292
+ t=json.dumps(payload, ensure_ascii=False),
293
+ exp=expires_at,
294
+ )
295
+
296
+
297
+ def onenote_token_get(user_id: str) -> dict | None:
298
+ try:
299
+ token = db.scalar("SELECT token FROM onenote_tokens WHERE user_id = :u", u=str(user_id))
300
+ except Exception:
301
+ logger.warning("OneNote token lookup failed for %s", user_id, exc_info=True)
302
+ return None
303
+ return token if isinstance(token, dict) else None
304
+
305
+
306
+ def onenote_token_delete(user_id: str) -> None:
307
+ db.execute("DELETE FROM onenote_tokens WHERE user_id = :u", u=str(user_id))
backend/study_store.py CHANGED
@@ -1,9 +1,8 @@
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
@@ -12,33 +11,17 @@ 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]
@@ -48,88 +31,62 @@ def create_deck(user_id: str, name: str, source_path: str, cards: list[dict]) ->
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:
@@ -157,78 +114,66 @@ def schedule(meta: dict, grade: str, now: int) -> dict:
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
 
@@ -280,49 +225,32 @@ def build_exam_plan(files: list[str], exam_day: dt.date, today: dt.date) -> list
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
 
1
  """
2
+ Saved flashcard decks with spaced repetition, quiz results and exam plans (tables in db.SCHEMA).
3
 
4
+ A card's schedule is stored on the card (due_at, interval_days, ease, reps, lapses), so "what's due"
5
+ is a simple query. Scheduling is a simplified SM-2 (the algorithm behind Anki's original scheduler).
 
6
  """
7
  import csv
8
  import datetime as dt
 
11
  import time
12
  import uuid
13
 
14
+ from backend import db
 
 
 
 
 
 
 
 
 
15
 
16
  GRADES = ("again", "hard", "good", "easy")
17
  MAX_CARDS_PER_DECK = 200
18
+ MAX_FIELD_CHARS = 4000
19
  RELEARN_SECONDS = 600 # "again" shows the card again in 10 minutes
20
  DAY = 86400
21
 
22
 
 
 
 
 
 
23
  def create_deck(user_id: str, name: str, source_path: str, cards: list[dict]) -> dict:
 
24
  now = int(time.time())
 
25
  clean = []
26
  for c in cards[:MAX_CARDS_PER_DECK]:
27
  front = str(c.get("front") or "").strip()[:MAX_FIELD_CHARS]
 
31
  if not clean:
32
  raise ValueError("A deck needs at least one card with a front and a back.")
33
  name = (name or "").strip()[:120] or "Flashcards"
34
+ deck_id = uuid.uuid4().hex[:16]
35
+ with db.transaction() as conn:
36
+ db.execute(
37
+ "INSERT INTO decks (id, user_id, name, source_path, created_at) VALUES (:id, :u, :name, :src, :now)",
38
+ conn, id=deck_id, u=user_id, name=name, src=(source_path or "")[:1000], now=now,
39
+ )
40
+ for i, c in enumerate(clean):
41
+ db.execute(
42
+ "INSERT INTO cards (id, deck_id, user_id, position, front, back, source, due_at) "
43
+ "VALUES (:id, :deck, :u, :pos, :front, :back, :source, :now)",
44
+ conn, id=f"card_{uuid.uuid4().hex[:20]}", deck=deck_id, u=user_id, pos=i, now=now, **c,
45
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  return {"deck_id": deck_id, "name": name, "card_count": len(clean)}
47
 
48
 
49
  def list_decks(user_id: str) -> list[dict]:
50
+ found = db.rows(
51
+ "SELECT d.id, d.name, d.source_path, d.created_at, count(c.id) AS card_count, "
52
+ "count(c.id) FILTER (WHERE c.due_at <= :now) AS due_count "
53
+ "FROM decks d LEFT JOIN cards c ON c.deck_id = d.id "
54
+ "WHERE d.user_id = :u GROUP BY d.id ORDER BY d.created_at DESC",
55
+ u=user_id, now=int(time.time()),
56
+ )
57
+ return [{
58
+ "deck_id": r["id"],
59
+ "name": r["name"] or "Flashcards",
60
+ "source_path": r["source_path"] or "",
61
+ "card_count": int(r["card_count"]),
62
+ "due_count": int(r["due_count"]),
63
+ "created_at": int(r["created_at"]),
64
+ } for r in found]
 
 
 
 
 
 
 
 
65
 
66
 
67
+ def _deck(user_id: str, deck_id: str) -> dict | None:
68
+ return db.one("SELECT * FROM decks WHERE id = :id AND user_id = :u", id=deck_id, u=user_id)
69
 
70
 
71
  def deck_cards(user_id: str, deck_id: str, due_only: bool, limit: int) -> list[dict] | None:
72
  """Cards of a deck (None if the deck doesn't exist). due_only: cards due now, soonest first."""
73
+ if not _deck(user_id, deck_id):
 
74
  return None
75
+ found = db.rows(
76
+ "SELECT * FROM cards WHERE deck_id = :d AND user_id = :u"
77
+ + (" AND due_at <= :now" if due_only else "")
78
+ + " ORDER BY due_at, position LIMIT :limit",
79
+ d=deck_id, u=user_id, now=int(time.time()), limit=max(1, min(limit, MAX_CARDS_PER_DECK)),
80
+ )
81
+ return [{
82
+ "card_id": r["id"],
83
+ "front": r["front"],
84
+ "back": r["back"],
85
+ "source": r["source"],
86
+ "due_at": int(r["due_at"]),
87
+ "interval_days": float(r["interval_days"]),
88
+ "reps": int(r["reps"]),
89
+ } for r in found]
 
 
 
 
90
 
91
 
92
  def schedule(meta: dict, grade: str, now: int) -> dict:
 
114
  def review_card(user_id: str, card_id: str, grade: str) -> dict | None:
115
  if grade not in GRADES:
116
  raise ValueError("Grade must be one of: again, hard, good, easy.")
117
+ with db.transaction() as conn:
118
+ row = db.one("SELECT * FROM cards WHERE id = :id AND user_id = :u FOR UPDATE", conn, id=card_id, u=user_id)
119
+ if not row:
120
+ return None
121
+ new = schedule(row, grade, int(time.time()))
122
+ db.execute(
123
+ "UPDATE cards SET due_at = :due_at, interval_days = :interval_days, ease = :ease, reps = :reps, "
124
+ "lapses = :lapses WHERE id = :id",
125
+ conn, id=card_id, **{k: new[k] for k in ("due_at", "interval_days", "ease", "reps", "lapses")},
126
+ )
127
+ return {"card_id": card_id, "due_at": new["due_at"], "interval_days": new["interval_days"]}
128
 
129
 
130
  def delete_deck(user_id: str, deck_id: str) -> bool:
131
+ return db.execute("DELETE FROM decks WHERE id = :id AND user_id = :u", id=deck_id, u=user_id) > 0
 
 
 
 
 
132
 
133
 
134
  def export_csv(user_id: str, deck_id: str) -> tuple[str, str] | None:
135
  """(deck name, CSV text with front,back rows) for importing into Anki, or None."""
136
+ deck = _deck(user_id, deck_id)
137
+ if not deck:
 
 
 
138
  return None
 
139
  buf = io.StringIO()
140
  writer = csv.writer(buf)
141
+ for r in db.rows("SELECT front, back FROM cards WHERE deck_id = :d ORDER BY position", d=deck_id):
142
+ writer.writerow([r["front"], r["back"]])
143
+ return deck["name"] or "flashcards", buf.getvalue()
144
 
145
 
146
  def delete_all(user_id: str) -> None:
147
+ """Every deck, card, quiz result and exam plan of a user."""
148
+ with db.transaction() as conn:
149
+ for table in ("cards", "decks", "quiz_results", "exams"):
150
+ db.execute(f"DELETE FROM {table} WHERE user_id = :u", conn, u=user_id)
151
 
152
 
153
  def due_count(user_id: str, until: int | None = None) -> int:
154
  """Number of cards due by `until` (epoch seconds; default now) across all decks."""
 
 
 
155
  until = int(until if until is not None else time.time())
156
+ return int(db.scalar("SELECT count(*) FROM cards WHERE user_id = :u AND due_at <= :t", u=user_id, t=until) or 0)
157
 
158
 
159
  # ---------- Quiz results per file (for "weak topics") ----------
160
  def mcq_record(user_id: str, path: str, correct: int, total: int) -> dict:
161
+ row = db.one(
162
+ "INSERT INTO quiz_results (user_id, path, correct, total, updated_at) VALUES (:u, :p, :c, :t, :now) "
163
+ "ON CONFLICT (user_id, path) DO UPDATE SET correct = quiz_results.correct + EXCLUDED.correct, "
164
+ "total = quiz_results.total + EXCLUDED.total, updated_at = EXCLUDED.updated_at RETURNING *",
165
+ u=user_id, p=path[:1000], c=int(correct), t=int(total), now=int(time.time()),
166
+ )
167
+ return {"path": row["path"], "correct": int(row["correct"]), "total": int(row["total"]), "updated_at": int(row["updated_at"])}
 
 
168
 
169
 
170
  def weak_topics(user_id: str, min_answered: int = 3, below: float = 0.7, limit: int = 5) -> list[dict]:
171
  """Files whose quiz accuracy is lowest (only files with at least `min_answered` answers)."""
 
 
 
172
  out = []
173
+ for r in db.rows("SELECT path, correct, total FROM quiz_results WHERE user_id = :u", u=user_id):
174
+ total, correct = int(r["total"]), int(r["correct"])
175
  if total >= min_answered and correct / total < below:
176
+ out.append({"path": r["path"], "correct": correct, "total": total, "accuracy": round(correct / total, 3)})
177
  out.sort(key=lambda t: (t["accuracy"], -t["total"]))
178
  return out[:limit]
179
 
 
225
  return plan
226
 
227
 
228
+ def _exam_public(row: dict, today: dt.date) -> dict:
229
+ exam_day = row["exam_date"]
230
  return {
231
+ "exam_id": row["id"],
232
+ "course": row["course"] or "",
233
+ "exam_date": exam_day.isoformat(),
234
  "days_left": (exam_day - today).days,
235
+ "plan": row["plan"] if isinstance(row["plan"], list) else json.loads(row["plan"] or "[]"),
236
  }
237
 
238
 
239
  def save_exam(user_id: str, course: str, files: list[str], exam_day: dt.date, today: dt.date) -> dict:
240
  plan = build_exam_plan(files, exam_day, today)
241
+ row = db.one(
242
+ "INSERT INTO exams (id, user_id, course, exam_date, plan, created_at) "
243
+ "VALUES (:id, :u, :course, :day, CAST(:plan AS jsonb), :now) RETURNING *",
244
+ id=uuid.uuid4().hex[:16], u=user_id, course=course[:500], day=exam_day,
245
+ plan=json.dumps(plan, ensure_ascii=False), now=int(time.time()),
246
+ )
247
+ return _exam_public(row, today)
 
 
 
 
 
 
 
 
248
 
249
 
250
  def list_exams(user_id: str, today: dt.date) -> list[dict]:
251
+ found = db.rows("SELECT * FROM exams WHERE user_id = :u ORDER BY exam_date, created_at", u=user_id)
252
+ return [_exam_public(r, today) for r in found]
 
 
 
 
 
253
 
254
 
255
  def delete_exam(user_id: str, exam_id: str) -> bool:
256
+ return db.execute("DELETE FROM exams WHERE id = :id AND user_id = :u", id=exam_id, u=user_id) > 0
 
 
 
 
backend/uploads.py CHANGED
@@ -15,11 +15,10 @@ 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
@@ -85,8 +84,8 @@ def _read_pdf(data: bytes) -> Extracted:
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)
@@ -107,10 +106,10 @@ def extract_text(raw_name: str, data: bytes) -> Extracted:
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:
@@ -138,11 +137,11 @@ def extract_text_or_http_error(raw_name: str, data: bytes) -> Extracted:
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)
@@ -183,7 +182,10 @@ def _process(job_id: str, user_id: str, folder: str, raw_name: str, data: bytes)
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))
 
15
 
16
  from fastapi import HTTPException, UploadFile
17
 
18
+ from backend import alerts, ocr, originals, usage
 
 
 
19
  from backend.pages import PageStarts, anchor_page_starts, join_pages, pdf_page_texts
20
+ from backend.pipeline.indexing import index_note
21
+ from backend.store import user_document_upsert, user_lock, vfs_set_tree
22
  from backend.paths import get_vfs_tree_clean
23
  from backend.settings import MAX_ACTIVE_UPLOADS_PER_USER, MAX_UPLOAD_BYTES, MAX_UPLOAD_MB
24
  from backend.vfs_tree import tree_add_file
 
84
  local_pages = pdf_page_texts(data)
85
  except Exception as e: # not a readable PDF for PyMuPDF; Sarvam may still manage
86
  local_pages, local_error = [], e
87
+ text, note, ai_pages = ocr.transcribe_pdf_with_pages(data)
88
+ sent = (len(local_pages) or 1) if ocr.sarvam_api_key() else 0
89
  if (text or "").strip():
90
  # Find each page inside Sarvam's text: its own per-page text first, else PyMuPDF's.
91
  starts = anchor_page_starts(text, ai_pages) or anchor_page_starts(text, local_pages)
 
106
  if ext == ".pdf":
107
  result = _read_pdf(data)
108
  elif ext in IMAGE_MIME_TYPES:
109
+ text, note = ocr.transcribe_handwritten_image(data, IMAGE_MIME_TYPES[ext])
110
+ sent = 1 if ocr.sarvam_api_key() else 0
111
  if not (text or "").strip():
112
+ text = ocr.tesseract_image_text(data)
113
  note = note or "used_tesseract_fallback"
114
  result = Extracted(text, note or "", None, sent)
115
  else:
 
137
  def save_note_text(user_id: str, folder: str, raw_name: str, text: str, page_starts: PageStarts | None = None) -> dict:
138
  """Save text for search and as the file's stored text, then add the file to the tree."""
139
  rel_path = f"{folder}/{raw_name}" if folder else raw_name
140
+ ingest_result = index_note(user_id, rel_path, raw_name, text, page_starts)
141
  try:
142
  user_document_upsert(user_id, rel_path, text, raw_name)
143
  except Exception:
144
+ # The passages make it searchable; the full-text copy is used for viewing, editing and study tools.
145
  logger.warning("Stored-text write failed for %s", rel_path, exc_info=True)
146
  with user_lock(user_id):
147
  tree = get_vfs_tree_clean(user_id)
 
182
  extracted = extract_text(raw_name, data)
183
  usage.record(user_id, pages_read=extracted.pages_sent_to_ai)
184
  result = save_note_text(user_id, folder, raw_name, extracted.text, extracted.page_starts)
185
+ # Keep the PDF/photo itself too, so it opens on any device.
186
+ kept = originals.keep(user_id, f"{folder}/{raw_name}" if folder else raw_name, raw_name, data)
187
+ message = f"Ready: {result.get('chunks_created', 0)} searchable sections."
188
+ _set(job_id, status="done", message=f"{message} {kept}" if kept else message)
189
  except ExtractionError as e:
190
  usage.record(user_id, upload_failures=1)
191
  _set(job_id, status="failed", error=str(e))
backend/usage.py CHANGED
@@ -2,7 +2,7 @@
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
@@ -12,8 +12,7 @@ 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
 
@@ -49,10 +48,6 @@ 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)
@@ -74,32 +69,36 @@ def record(user_id: str, **increments: int) -> None:
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:
@@ -107,8 +106,14 @@ def month_cost(now: float | None = None) -> float:
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
 
@@ -124,7 +129,7 @@ def check_budget() -> None:
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
 
@@ -135,7 +140,4 @@ def reset_cache() -> None:
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"])
 
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 row per user per day in the usage_daily table (one column per counter).
6
  """
7
  import datetime as dt
8
  import logging
 
12
 
13
  from fastapi import HTTPException
14
 
15
+ from backend import db, settings
 
16
 
17
  logger = logging.getLogger(__name__)
18
 
 
48
  return day.year * 10000 + day.month * 100 + day.day
49
 
50
 
 
 
 
 
51
  def prices_set() -> bool:
52
  return any(
53
  (settings.AI_PRICE_PER_PAGE, settings.AI_PRICE_PER_1K_INPUT_TOKENS, settings.AI_PRICE_PER_1K_OUTPUT_TOKENS)
 
69
  return
70
  day = today()
71
  month = f"{day.year:04d}-{day.month:02d}"
72
+ cols = ", ".join(increments) # names come from COUNTERS only
73
  try:
74
+ db.execute(
75
+ f"INSERT INTO usage_daily (user_id, day, {cols}) VALUES (:u, :day, "
76
+ + ", ".join(f":{k}" for k in increments)
77
+ + ") ON CONFLICT (user_id, day) DO UPDATE SET "
78
+ + ", ".join(f"{k} = usage_daily.{k} + EXCLUDED.{k}" for k in increments),
79
+ u=user_id,
80
+ day=day,
81
+ **increments,
82
+ )
83
  with _lock:
 
 
 
 
 
 
 
 
 
 
 
84
  if month in _month_cost:
85
  _month_cost[month] += cost_of(increments)
86
  except Exception:
87
  logger.warning("Usage counting failed for %s", user_id, exc_info=True)
88
 
89
 
90
+ def _public(row: dict) -> dict:
91
+ day = row["day"]
92
+ return {**{k: int(row[k]) for k in COUNTERS}, "user_id": row["user_id"], "day": day.isoformat(),
93
+ "day_num": day_num(day), "month": f"{day.year:04d}-{day.month:02d}"}
94
+
95
+
96
  def records_since(start: dt.date, user_id: str | None = None) -> list[dict]:
 
97
  if user_id:
98
+ found = db.rows("SELECT * FROM usage_daily WHERE day >= :d AND user_id = :u", d=start, u=user_id)
99
+ else:
100
+ found = db.rows("SELECT * FROM usage_daily WHERE day >= :d", d=start)
101
+ return [_public(r) for r in found]
102
 
103
 
104
  def month_cost(now: float | None = None) -> float:
 
106
  month = f"{day.year:04d}-{day.month:02d}"
107
  with _lock:
108
  if month not in _month_cost:
109
+ first = day.replace(day=1)
110
+ sums = db.one(
111
+ "SELECT " + ", ".join(f"coalesce(sum({k}), 0) AS {k}" for k in COUNTERS)
112
+ + " FROM usage_daily WHERE day >= :first AND day <= :day",
113
+ first=first,
114
+ day=day,
115
+ )
116
+ _month_cost[month] = cost_of(sums or {})
117
  return _month_cost[month]
118
 
119
 
 
129
  if spent >= settings.AI_MONTHLY_BUDGET:
130
  raise HTTPException(
131
  status_code=503,
132
+ detail="Study AI has used this month's AI budget, so reading files, answers and study "
133
  "tools are paused until next month. Your notes and flashcard reviews still work.",
134
  )
135
 
 
140
 
141
 
142
  def delete_user(user_id: str) -> None:
143
+ db.execute("DELETE FROM usage_daily WHERE user_id = :u", u=user_id)
 
 
 
backend/vfs_tree.py CHANGED
@@ -1,4 +1,4 @@
1
- """Virtual folder tree mutations (explorer). Stored in ChromaDB, not on disk."""
2
  from __future__ import annotations
3
 
4
  import copy
 
1
+ """Virtual folder tree changes (explorer). The tree is stored in the database (folders table), not on disk."""
2
  from __future__ import annotations
3
 
4
  import copy
requirements.txt CHANGED
@@ -1,6 +1,5 @@
1
  fastapi==0.116.2
2
  uvicorn==0.35.0
3
- langchain-text-splitters==0.3.11
4
  httpx==0.28.1
5
  sarvamai==0.1.35
6
  pytesseract==0.3.13
@@ -10,8 +9,18 @@ transformers==4.56.1
10
  torch==2.8.0
11
  sentence-transformers==5.1.0
12
  numpy==2.3.3
13
- chromadb==1.0.21
14
  pymupdf==1.26.4
15
  python-multipart==0.0.20
16
- passlib[bcrypt]==1.7.4
17
- bcrypt==4.0.1
 
 
 
 
 
 
 
 
 
 
 
 
1
  fastapi==0.116.2
2
  uvicorn==0.35.0
 
3
  httpx==0.28.1
4
  sarvamai==0.1.35
5
  pytesseract==0.3.13
 
9
  torch==2.8.0
10
  sentence-transformers==5.1.0
11
  numpy==2.3.3
 
12
  pymupdf==1.26.4
13
  python-multipart==0.0.20
14
+ # Database: Postgres with pgvector
15
+ SQLAlchemy==2.0.43
16
+ psycopg2-binary==2.9.13
17
+ asyncpg==0.32.0
18
+ pgvector==0.5.1
19
+ # Students' original files (Neon Object Storage, S3-compatible)
20
+ boto3==1.43.113
21
+ # The notes pipeline (LlamaIndex)
22
+ llama-index-core==0.14.25
23
+ llama-index-vector-stores-postgres==0.9.0
24
+ llama-index-embeddings-huggingface==0.8.0
25
+ llama-index-llms-sarvam==0.4.1
26
+ llama-index-llms-openai-like==0.8.1