Dipti Dhawade commited on
Commit
c5ca5f9
·
0 Parent(s):

HF Space deploy snapshot without binary artifacts

Browse files
.dockerignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ node_modules
2
+ dist
3
+ *.log
4
+ .env
5
+ .git
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.github/workflows/deploy.yml ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Deploy to GitHub Pages
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+
7
+ permissions:
8
+ contents: read
9
+ pages: write
10
+ id-token: write
11
+
12
+ concurrency:
13
+ group: "pages"
14
+ cancel-in-progress: false
15
+
16
+ jobs:
17
+ build-and-deploy:
18
+ runs-on: ubuntu-latest
19
+ environment: github-pages
20
+ steps:
21
+ - name: Checkout
22
+ uses: actions/checkout@v4
23
+
24
+ - name: Setup Node
25
+ uses: actions/setup-node@v4
26
+ with:
27
+ node-version: "20"
28
+
29
+ - name: Install and build
30
+ working-directory: frontend/my-app
31
+ env:
32
+ VITE_API_URL: ${{ secrets.VITE_API_URL }}
33
+ run: |
34
+ if [ -z "$VITE_API_URL" ]; then
35
+ echo "VITE_API_URL secret is missing. Add your backend URL (e.g. https://diptidhawade-NoteScanner.hf.space)." >&2
36
+ exit 1
37
+ fi
38
+ npm ci
39
+ npm run build
40
+
41
+ - name: Upload artifact
42
+ uses: actions/upload-pages-artifact@v3
43
+ with:
44
+ path: frontend/my-app/dist
45
+
46
+ deploy:
47
+ runs-on: ubuntu-latest
48
+ needs: build-and-deploy
49
+ environment: github-pages
50
+ steps:
51
+ - name: Deploy to GitHub Pages
52
+ uses: actions/deploy-pages@v4
.gitignore ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.pyc
4
+ *.pyo
5
+ *.pyd
6
+
7
+ # Virtual Environments
8
+ venv/
9
+ .venv/
10
+
11
+ # ChromaDB (legacy local storage; app uses Docker Chroma server)
12
+ chroma_storage/
13
+
14
+ # User data
15
+ user_notes/
16
+
17
+ # Node
18
+ node_modules/
19
+ package-lock.json
20
+
21
+ # System/Editor
22
+ .DS_Store
23
+ Thumbs.db
24
+ .vscode/
25
+ .idea/
26
+ .env
27
+
28
+ # Machine Learning binaries
29
+ *.pth
30
+ *.pt
31
+ *.h5
32
+ *.ckpt
33
+ *.joblib
34
+ *.pkl
35
+ *.npy
36
+ *.npz
37
+ *.dylib
38
+ *.so
39
+ *.onnx
40
+
41
+ # Logs
42
+ *.log
43
+
44
+ # ML output folders
45
+ runs/
46
+ output/
47
+ checkpoints/
48
+ *.tensorboard/
DEPLOYMENT.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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. In **Files**, upload this repository content (or push from git).
12
+ 3. Ensure the Space uses the root `Dockerfile` (already configured to run on `${PORT}` with default `7860`).
13
+ 4. In Space **Settings -> Variables and secrets**, add:
14
+
15
+ ### Required Space secrets
16
+
17
+ - `SARVAM_API_KEY`
18
+
19
+ ### Recommended Space variables/secrets
20
+
21
+ - `SARVAM_API_BASE` (optional, default works)
22
+ - `SARVAM_MODEL_RAG` (optional)
23
+ - `SARVAM_MODEL_STUDY` (optional)
24
+ - `SARVAM_DOC_INTEL_LANGUAGE` (optional)
25
+ - `SARVAM_DOC_INTEL_TIMEOUT` (optional)
26
+
27
+ ### Chroma (required for persistent note features)
28
+
29
+ Use one option:
30
+
31
+ - Chroma Cloud:
32
+ - `CHROMA_API_KEY`
33
+ - `CHROMA_TENANT`
34
+ - `CHROMA_DATABASE`
35
+ - OR self-hosted Chroma:
36
+ - `CHROMA_HOST`
37
+ - `CHROMA_PORT`
38
+ - `CHROMA_SSL` (optional)
39
+
40
+ 1. Wait for Space build to finish.
41
+ 2. Copy backend URL, e.g. `https://diptidhawade-NoteScanner.hf.space`
42
+
43
+ ## 2) Configure GitHub Pages frontend
44
+
45
+ 1. In your GitHub repo, go to **Settings -> Secrets and variables -> Actions -> New repository secret**.
46
+ 2. Add this secret:
47
+
48
+ - `VITE_API_URL` = `https://diptidhawade-NoteScanner.hf.space`
49
+
50
+ 1. Push to `main` (or rerun workflow `Deploy to GitHub Pages`).
51
+ 2. GitHub Pages URL will be:
52
+ - `https://<your-username>.github.io/NoteScanner/`
53
+
54
+ ## 3) Verify
55
+
56
+ 1. Open frontend URL.
57
+ 2. Confirm these work:
58
+ - `+` chat upload
59
+ - query response
60
+ - explorer upload
61
+ - study generation
62
+
63
+ ## Notes
64
+
65
+ - Backend on free HF Space may sleep when idle (cold start delay on first request).
66
+ - If frontend shows backend/network errors, first check `VITE_API_URL` secret and Space build logs.
DEPLOYMENT_FREE.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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. In **Files**, upload this repository content (or push from git).
12
+ 3. Ensure the Space uses the root `Dockerfile` (already configured to run on `${PORT}` with default `7860`).
13
+ 4. In Space **Settings -> Variables and secrets**, add:
14
+
15
+ ### Required Space secrets
16
+
17
+ - `SARVAM_API_KEY`
18
+
19
+ ### Recommended Space variables/secrets
20
+
21
+ - `SARVAM_API_BASE` (optional, default works)
22
+ - `SARVAM_MODEL_RAG` (optional)
23
+ - `SARVAM_MODEL_STUDY` (optional)
24
+ - `SARVAM_DOC_INTEL_LANGUAGE` (optional)
25
+ - `SARVAM_DOC_INTEL_TIMEOUT` (optional)
26
+
27
+ ### Chroma (required for persistent note features)
28
+
29
+ Use one option:
30
+
31
+ - Chroma Cloud:
32
+ - `CHROMA_API_KEY`
33
+ - `CHROMA_TENANT`
34
+ - `CHROMA_DATABASE`
35
+ - OR self-hosted Chroma:
36
+ - `CHROMA_HOST`
37
+ - `CHROMA_PORT`
38
+ - `CHROMA_SSL` (optional)
39
+
40
+ 1. Wait for Space build to finish.
41
+ 2. Copy backend URL, e.g. `https://diptidhawade-NoteScanner.hf.space`
42
+
43
+ ## 2) Configure GitHub Pages frontend
44
+
45
+ 1. In your GitHub repo, go to **Settings -> Secrets and variables -> Actions -> New repository secret**.
46
+ 2. Add this secret:
47
+
48
+ - `VITE_API_URL` = `https://diptidhawade-NoteScanner.hf.space`
49
+
50
+ 1. Push to `main` (or rerun workflow `Deploy to GitHub Pages`).
51
+ 2. GitHub Pages URL will be:
52
+ - `https://<your-username>.github.io/NoteScanner/`
53
+
54
+ ## 3) Verify
55
+
56
+ 1. Open frontend URL.
57
+ 2. Confirm these work:
58
+ - `+` chat upload
59
+ - query response
60
+ - explorer upload
61
+ - study generation
62
+
63
+ ## Notes
64
+
65
+ - Backend on free HF Space may sleep when idle (cold start delay on first request).
66
+ - If frontend shows backend/network errors, first check `VITE_API_URL` secret and Space build logs.
Dockerfile ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ WORKDIR /app
4
+
5
+ RUN apt-get update && apt-get install -y build-essential tesseract-ocr
6
+
7
+ COPY requirements.txt .
8
+ RUN pip install --no-cache-dir -r requirements.txt
9
+
10
+ COPY . .
11
+
12
+ ENV PYTHONUNBUFFERED=1
13
+ ENV PORT=7860
14
+
15
+ CMD ["sh", "-c", "uvicorn backend.api:app --host 0.0.0.0 --port ${PORT:-7860}"]
README.md ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NoteScanner
2
+
3
+ NoteScanner is a FastAPI + React platform for uploading notes, extracting text, indexing with embeddings, and generating grounded learning outputs.
4
+
5
+ Core capabilities:
6
+
7
+ - Upload PDFs/images/text and extract text with Vision OCR.
8
+ - Store persistent note chunks + embeddings in ChromaDB for retrieval.
9
+ - Support temporary chat-only uploads from the chatbot `+` button (ephemeral cache, no DB persistence).
10
+ - Answer questions and generate flashcards/MCQs/mind maps from retrieved context.
11
+
12
+ NoteScanner uploads course materials, indexes them in ChromaDB, and uses **Sarvam AI**: **Document Intelligence (Sarvam Vision)** for PDF/image OCR and **Chat Completions** (`sarvam-30b` / `sarvam-105b`) for note-grounded Q&A, flashcards, MCQs, and mind maps. Tesseract remains a fallback extractor. It features a FastAPI backend and a React/Vite frontend, orchestrated with Docker Compose.
13
+
14
+ You upload your handwritten notes → the system scans, organizes, and lets you chat with your notes using Retrieval-Augmented Generation (RAG).
15
+
16
+ NoteScanner Demo
17
+
18
+ ## Prerequisites
19
+
20
+ - Docker & Docker Compose
21
+ - Python 3.10+
22
+ - Node.js 20+
23
+
24
+ ## System Architecture
25
+
26
+ - `frontend/my-app`: React + Vite UI
27
+ - `backend/api.py`: FastAPI API layer
28
+ - `backend/chroma_store.py`: Chroma client + collection accessors
29
+ - `backend/ingest_api.py`: chunking + embedding ingestion
30
+ - `backend/llm_pipeline.py`: OCR + LLM calls
31
+ - `backend/vfs_tree.py`: virtual folder tree helpers
32
+ - `backend/file_meta.py`: file metadata policy layer
33
+
34
+ ## End-to-End Pipeline
35
+
36
+ ### 1) Persistent note upload pipeline (Explorer)
37
+
38
+ Endpoint: `POST /upload_note`
39
+
40
+ Flow:
41
+
42
+ 1. Client uploads file to backend.
43
+ 2. Backend reads file bytes in memory.
44
+ 3. Text extraction:
45
+ - PDF: Sarvam Document Intelligence first, parser fallback.
46
+ - Image: Sarvam Vision OCR first, Tesseract fallback.
47
+ - Plain text formats: UTF-8 decode.
48
+ 4. Backend persists:
49
+ - full extracted text in `user_documents`,
50
+ - chunked text + embeddings in `user_{user_id}_notes`.
51
+ 5. VFS is updated for explorer visibility.
52
+
53
+ ### 2) Ephemeral chatbot `+` upload pipeline
54
+
55
+ Endpoint: `POST /chat/upload_ephemeral`
56
+
57
+ Flow:
58
+
59
+ 1. Frontend sends file with `chat_session_id`.
60
+ 2. Backend extracts text in memory.
61
+ 3. Backend stores extracted text in process memory cache keyed by `(user_id, chat_session_id)`.
62
+
63
+ Important:
64
+
65
+ - No `user_documents` write.
66
+ - No `user_{user_id}_notes` write.
67
+ - No Chroma persistence for this path.
68
+
69
+ Cache clear:
70
+
71
+ - `POST /chat/session/clear`
72
+ - Triggered by chat refresh/new chat/unmount.
73
+
74
+ ### 3) Query retrieval sequence (implemented priority)
75
+
76
+ Endpoint: `POST /query_folder`
77
+
78
+ Retrieval order:
79
+
80
+ 1. Ephemeral chat uploads (`+` cache)
81
+ 2. Opened file in viewer
82
+ 3. Other files in same course folder
83
+
84
+ Selection logic:
85
+
86
+ - Embedding-based relevance scoring is computed per stage.
87
+ - The highest-priority relevant stage is selected.
88
+ - If relevance is weak at a higher stage, system falls to next stage.
89
+ - This reduces unrelated-domain leakage (for example RL queries answered from generic ML notes).
90
+
91
+ ### 4) Study generation pipeline
92
+
93
+ Endpoints:
94
+
95
+ - `POST /study/generate` (task: `flashcards` or `mcq`)
96
+ - `POST /study/mindmap`
97
+
98
+ Context policy:
99
+
100
+ - Opened file is primary context.
101
+ - Same-course files can be included as supporting context.
102
+
103
+ ## API Reference (Main Endpoints)
104
+
105
+ ### Authentication
106
+
107
+ - `POST /register`
108
+ - `POST /login`
109
+ - `GET /me`
110
+ - `GET /guest_id`
111
+
112
+ ### Notes and VFS
113
+
114
+ - `GET /list_tree`
115
+ - `POST /create_folder`
116
+ - `POST /create_file`
117
+ - `POST /upload_note`
118
+ - `POST /move_path`
119
+ - `POST /delete_path`
120
+ - `DELETE /notes`
121
+ - `GET /file_meta`
122
+ - `POST /file_meta`
123
+
124
+ ### Query and chat uploads
125
+
126
+ - `POST /query_folder`
127
+ - `POST /chat/upload_ephemeral`
128
+ - `POST /chat/session/clear`
129
+
130
+ ### Study tools
131
+
132
+ - `POST /study/generate`
133
+ - `POST /study/mindmap`
134
+
135
+ ### OneNote integration
136
+
137
+ - `GET /integrations/onenote/status`
138
+ - `GET /integrations/onenote/auth_url`
139
+ - `GET /integrations/onenote/callback`
140
+ - `POST /integrations/onenote/sync`
141
+
142
+ ## Database and Collection Design
143
+
144
+ Chroma is used as central storage for both metadata and vector retrieval.
145
+
146
+ Collections:
147
+
148
+ - `users`: email, hashed password, name
149
+ - `sessions`: session_id -> user_id
150
+ - `user_documents`: full extracted text per logical path
151
+ - `user_{user_id}_notes`: chunk docs + embeddings + chunk metadata
152
+ - `user_{user_id}_vfs`: virtual tree + file meta JSON
153
+ - `onenote_tokens`: OAuth tokens
154
+ - `onenote_oauth_states`: OAuth state for callback
155
+
156
+ Notes:
157
+
158
+ - Guest mode uses effective IDs like `guest_<uuid>`.
159
+ - Persistent note uploads are stored/indexed.
160
+ - Chatbot `+` uploads are intentionally ephemeral.
161
+
162
+ ## LLM and OCR Implementation
163
+
164
+ From `backend/llm_pipeline.py`:
165
+
166
+ - OCR:
167
+ - Sarvam Document Intelligence / Vision for PDF-image text extraction.
168
+ - Local fallback extractors where needed.
169
+ - Q&A:
170
+ - `sarvam_rag_answer(question, context)`
171
+ - Study generation:
172
+ - `cheap_study_json(context, task, n)` for flashcards/MCQ
173
+ - `mind_map_json(context)` for mind maps
174
+
175
+ Model env controls:
176
+
177
+ - `SARVAM_MODEL_RAG` (default: `sarvam-105b`)
178
+ - `SARVAM_MODEL_STUDY` (default: `sarvam-30b`)
179
+
180
+ ## Configuration
181
+
182
+ Required:
183
+
184
+ - `SARVAM_API_KEY`
185
+
186
+ Optional Sarvam:
187
+
188
+ - `SARVAM_API_BASE` (default `https://api.sarvam.ai`)
189
+ - `SARVAM_MODEL_RAG`
190
+ - `SARVAM_MODEL_STUDY`
191
+ - `SARVAM_DOC_INTEL_LANGUAGE` (default `en-IN`)
192
+ - `SARVAM_DOC_INTEL_TIMEOUT` (default `180`)
193
+
194
+ Chroma options:
195
+
196
+ - Cloud:
197
+ - `CHROMA_API_KEY`
198
+ - `CHROMA_TENANT`
199
+ - `CHROMA_DATABASE`
200
+ - Self-hosted:
201
+ - `CHROMA_HOST`
202
+ - `CHROMA_PORT`
203
+ - `CHROMA_SSL` (optional)
204
+
205
+ Other:
206
+
207
+ - `USER_DOCUMENT_MAX_BYTES`
208
+ - `MICROSOFT_CLIENT_ID`, `MICROSOFT_CLIENT_SECRET`, `MICROSOFT_REDIRECT_URI` (OneNote)
209
+
210
+ ## Run with Docker Compose
211
+
212
+ ```bash
213
+ docker compose up --build
214
+ ```
215
+
216
+ Services:
217
+
218
+ - Backend: `http://localhost:8000`
219
+ - Frontend: `http://localhost:5173`
220
+
221
+ Rebuild backend after backend changes:
222
+
223
+ ```bash
224
+ docker compose build backend && docker compose up -d backend
225
+ ```
226
+
227
+ ## Local Development (No Compose)
228
+
229
+ Backend:
230
+
231
+ ```bash
232
+ python3 -m venv venv
233
+ source venv/bin/activate
234
+ pip install -r requirements.txt
235
+ uvicorn backend.api:app --host 0.0.0.0 --port 8000
236
+ ```
237
+
238
+ Frontend:
239
+
240
+ ```bash
241
+ cd frontend/my-app
242
+ npm install
243
+ npm run dev -- --host
244
+ ```
245
+
246
+ ## Current Product Rules
247
+
248
+ - Chatbot `+` uploads are temporary per chat session.
249
+ - Temporary uploads are not persisted in Chroma collections.
250
+ - Query routing order is: chat cache -> open file -> same-course files.
251
+ - Chat refresh/new chat clears temporary cache.
252
+
253
+ ## Repository Layout
254
+
255
+ - `backend/` API, ingestion, retrieval, auth, VFS, LLM integration
256
+ - `frontend/my-app/` UI and interaction layer
257
+ - `docker-compose.yml` local orchestration
258
+ - `requirements.txt` backend dependencies
259
+
backend/api.py ADDED
@@ -0,0 +1,1181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File, Form, Depends, Request, HTTPException
2
+ from fastapi.responses import JSONResponse, HTMLResponse
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ import os
5
+ import re
6
+ import uuid
7
+ import time
8
+ from dotenv import load_dotenv
9
+ import copy
10
+ import json
11
+ from datetime import datetime
12
+ from typing import Annotated
13
+ from sentence_transformers import SentenceTransformer
14
+
15
+ from backend.chroma_store import (
16
+ user_exists_by_email,
17
+ user_create,
18
+ user_get_by_email,
19
+ user_get_by_id,
20
+ user_document_upsert,
21
+ user_document_delete_many,
22
+ user_document_delete_by_path,
23
+ get_user_collection,
24
+ delete_user_notes_collection,
25
+ delete_user_notes_by_paths,
26
+ vfs_get_tree,
27
+ vfs_set_tree,
28
+ delete_user_vfs_collection,
29
+ user_document_rename_path,
30
+ user_documents_relocate_prefix,
31
+ onenote_oauth_state_create,
32
+ onenote_oauth_state_pop_user_id,
33
+ onenote_token_get,
34
+ onenote_token_upsert,
35
+ user_document_get_content,
36
+ user_notes_concat_text_for_path,
37
+ )
38
+
39
+ from backend.file_meta import (
40
+ load_file_meta,
41
+ set_entry,
42
+ delete_key,
43
+ delete_keys_for_prefix,
44
+ chunk_paths_for_file,
45
+ file_meta_rename_path,
46
+ file_meta_relocate_prefix,
47
+ )
48
+ from backend.ingest_api import (
49
+ ingest_text_for_path,
50
+ refresh_metadata_for_paths,
51
+ chunks_relocate_path,
52
+ chunks_relocate_folder_prefix,
53
+ )
54
+ from backend.vfs_tree import (
55
+ tree_add_folder,
56
+ tree_add_file,
57
+ tree_remove_path,
58
+ tree_move_path,
59
+ tree_has_folder,
60
+ flatten_file_paths,
61
+ )
62
+ from backend import llm_pipeline
63
+ from backend import onenote_sync
64
+
65
+ from backend.auth import (
66
+ hash_password,
67
+ verify_password,
68
+ create_session,
69
+ get_user_id_from_session,
70
+ get_effective_user,
71
+ SESSION_HEADER,
72
+ GUEST_HEADER,
73
+ )
74
+
75
+ load_dotenv()
76
+
77
+ app = FastAPI()
78
+ _query_embed_model = None
79
+ _chat_upload_cache: dict[str, list[dict]] = {}
80
+
81
+ app.add_middleware(
82
+ CORSMiddleware,
83
+ allow_origins=["*"],
84
+ allow_credentials=True,
85
+ allow_methods=["*"],
86
+ allow_headers=["*"],
87
+ )
88
+
89
+
90
+ def _get_query_embedder():
91
+ global _query_embed_model
92
+ if _query_embed_model is None:
93
+ _query_embed_model = SentenceTransformer("all-MiniLM-L6-v2")
94
+ return _query_embed_model
95
+
96
+
97
+ def _chat_cache_key(user_id: str, chat_session_id: str) -> str:
98
+ return f"{user_id}::{(chat_session_id or '').strip()}"
99
+
100
+
101
+ def _chat_cache_add(user_id: str, chat_session_id: str, item: dict) -> None:
102
+ key = _chat_cache_key(user_id, chat_session_id)
103
+ if not key.endswith("::"):
104
+ _chat_upload_cache.setdefault(key, []).append(item)
105
+
106
+
107
+ def _chat_cache_items(user_id: str, chat_session_id: str) -> list[dict]:
108
+ key = _chat_cache_key(user_id, chat_session_id)
109
+ return list(_chat_upload_cache.get(key, []))
110
+
111
+
112
+ def _chat_cache_clear(user_id: str, chat_session_id: str) -> int:
113
+ key = _chat_cache_key(user_id, chat_session_id)
114
+ old = _chat_upload_cache.pop(key, [])
115
+ return len(old)
116
+
117
+ # ---------- Auth: register & login (simple session, no JWT) ----------
118
+ @app.post("/register")
119
+ def register(email: str = Form(...), password: str = Form(...), name: str = Form("")):
120
+ try:
121
+ if user_exists_by_email(email):
122
+ return JSONResponse({"error": "Email already registered."}, status_code=400)
123
+ user_id = user_create(
124
+ email.lower(),
125
+ hash_password(password),
126
+ name or email.split("@")[0],
127
+ )
128
+ session_id = create_session(user_id)
129
+ u = user_get_by_id(user_id)
130
+ display_name = (u and u.get("name")) or email.split("@")[0]
131
+ return JSONResponse({"session_id": session_id, "user_id": user_id, "name": display_name})
132
+ except Exception:
133
+ return JSONResponse(
134
+ {"error": "Database unavailable. Please try again later."},
135
+ status_code=503,
136
+ )
137
+
138
+
139
+ @app.post("/login")
140
+ def login(email: str = Form(...), password: str = Form(...)):
141
+ try:
142
+ user = user_get_by_email(email)
143
+ if not user or not verify_password(password, user["hashed_password"]):
144
+ return JSONResponse({"error": "Invalid email or password."}, status_code=401)
145
+ user_id = user["user_id"]
146
+ session_id = create_session(user_id)
147
+ name = user.get("name") or (user.get("email") or "").split("@")[0]
148
+ return JSONResponse({"session_id": session_id, "user_id": user_id, "name": name})
149
+ except Exception:
150
+ return JSONResponse(
151
+ {"error": "Database unavailable. Please try again later."},
152
+ status_code=503,
153
+ )
154
+
155
+
156
+ @app.get("/me")
157
+ def get_me(request: Request):
158
+ """Return current user info (name) for the session. Requires valid X-Session-Id."""
159
+ session_id = request.headers.get(SESSION_HEADER)
160
+ user_id = get_user_id_from_session(session_id)
161
+ if not user_id:
162
+ return JSONResponse({"error": "Not signed in."}, status_code=401)
163
+ user = user_get_by_id(user_id)
164
+ if not user:
165
+ return JSONResponse({"error": "User not found."}, status_code=404)
166
+ name = user.get("name") or (user.get("email") or "").split("@")[0]
167
+ return JSONResponse({"name": name or "User"})
168
+
169
+
170
+ @app.get("/guest_id")
171
+ def get_guest_id():
172
+ """Return a new guest id for anonymous use. Frontend stores it and sends X-Guest-Id header."""
173
+ return JSONResponse({"guest_id": str(uuid.uuid4())})
174
+
175
+
176
+ # ---------- Resolve user/guest from request ----------
177
+ def get_effective_user_dep(request: Request) -> tuple[str, bool]:
178
+ try:
179
+ return get_effective_user(request)
180
+ except ValueError as e:
181
+ raise HTTPException(status_code=400, detail=str(e))
182
+
183
+
184
+ def _require_signed_in(effective: tuple[str, bool]) -> str:
185
+ user_id, is_guest = effective
186
+ if is_guest:
187
+ raise HTTPException(status_code=401, detail="Sign in required for OneNote integration.")
188
+ return user_id
189
+
190
+
191
+ # ---------- Delete file or folder ----------
192
+ def _normalize_relative_path(path: str) -> str:
193
+ """Use forward slashes and strip leading slashes for cross-platform consistency."""
194
+ if not path or not path.strip():
195
+ return ""
196
+ return path.replace("\\", "/").strip("/")
197
+
198
+
199
+ def _is_likely_user_id_segment(seg: str) -> bool:
200
+ if not seg:
201
+ return False
202
+ if seg.startswith("guest_"):
203
+ return True
204
+ if len(seg) == 36 and seg.count("-") == 4:
205
+ return True
206
+ return False
207
+
208
+
209
+ def _strip_storage_path(p: str) -> str:
210
+ """
211
+ Remove legacy server-side prefixes from virtual paths so course folders stay at the root
212
+ (e.g. user_notes/<id>/Course/a.pdf -> Course/a.pdf). Never persist user_notes in vfs.
213
+ """
214
+ p = _normalize_relative_path(p)
215
+ if not p:
216
+ return ""
217
+ parts = [x for x in p.split("/") if x and x != "."]
218
+ while parts and parts[0].lower() == "user_notes":
219
+ parts.pop(0)
220
+ if parts and _is_likely_user_id_segment(parts[0]):
221
+ parts.pop(0)
222
+ return "/".join(parts)
223
+
224
+
225
+ def _normalize_vfs_tree(tree: list) -> list:
226
+ """Deep copy of explorer tree with every path passed through _strip_storage_path."""
227
+ out = copy.deepcopy(tree or [])
228
+
229
+ def rec(nodes: list) -> None:
230
+ for n in nodes:
231
+ if "path" in n:
232
+ n["path"] = _strip_storage_path(str(n.get("path") or ""))
233
+ if n.get("type") == "folder":
234
+ rec(n.get("children") or [])
235
+
236
+ rec(out)
237
+ return out
238
+
239
+
240
+ def _get_vfs_tree_clean(user_id: str) -> list:
241
+ """Return vfs tree with no user_notes/legacy id prefixes; persist if corrected."""
242
+ raw = vfs_get_tree(user_id)
243
+ fixed = _normalize_vfs_tree(raw)
244
+ if fixed != raw:
245
+ vfs_set_tree(user_id, fixed)
246
+ return fixed
247
+
248
+
249
+ def _vfs_entry_kind(tree: list, target_path: str) -> str | None:
250
+ """Return 'file', 'folder', or None if path is not in the virtual tree."""
251
+ tp = _strip_storage_path(target_path)
252
+ if not tp:
253
+ return None
254
+ if tp in {p.replace("\\", "/") for p in flatten_file_paths(tree)}:
255
+ return "file"
256
+
257
+ def folder_at(nodes: list) -> bool:
258
+ for n in nodes:
259
+ p = _normalize_relative_path(n.get("path") or "")
260
+ if n.get("type") == "folder":
261
+ if p == tp:
262
+ return True
263
+ if folder_at(n.get("children") or []):
264
+ return True
265
+ return False
266
+
267
+ return "folder" if folder_at(tree) else None
268
+
269
+
270
+ def _path_exists_in_vfs(tree: list, rel: str) -> bool:
271
+ rel = _strip_storage_path(rel)
272
+ if rel in {p.replace("\\", "/") for p in flatten_file_paths(tree)}:
273
+ return True
274
+
275
+ def folder_at(nodes: list) -> bool:
276
+ for n in nodes:
277
+ p = _normalize_relative_path(n.get("path") or "")
278
+ if n.get("type") == "folder":
279
+ if p == rel:
280
+ return True
281
+ if folder_at(n.get("children") or []):
282
+ return True
283
+ return False
284
+
285
+ return folder_at(tree)
286
+
287
+
288
+ @app.post("/delete_path")
289
+ def delete_path(
290
+ path: str = Form(...),
291
+ kind: str = Form(...), # "file" | "folder"
292
+ effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
293
+ ):
294
+ """Remove a file or folder from the virtual tree and Chroma (no server-side binaries)."""
295
+ user_id, _ = effective
296
+ path = _strip_storage_path(path)
297
+ if ".." in path:
298
+ return JSONResponse({"error": "Invalid path."}, status_code=400)
299
+ tree = _get_vfs_tree_clean(user_id)
300
+ if kind == "file":
301
+ if _vfs_entry_kind(tree, path) != "file":
302
+ return JSONResponse({"error": "Not a file or not found."}, status_code=400)
303
+ stem, extp = os.path.splitext(path)
304
+ vfs_set_tree(user_id, tree_remove_path(tree, path))
305
+ user_document_delete_by_path(user_id, path)
306
+ if extp:
307
+ user_document_delete_by_path(user_id, stem + ".txt")
308
+ try:
309
+ col = get_user_collection(user_id)
310
+ ids_to_drop = []
311
+ for p in (path, path.replace(os.path.splitext(path)[1], ".txt") if extp else path):
312
+ res = col.get(where={"path": p}, include=[])
313
+ ids_to_drop.extend(res.get("ids") or [])
314
+ if ids_to_drop:
315
+ col.delete(ids=ids_to_drop)
316
+ except Exception:
317
+ pass
318
+ delete_key(user_id, path)
319
+ if extp:
320
+ delete_key(user_id, stem + ".txt")
321
+ return JSONResponse({"message": "File deleted."})
322
+ if kind == "folder":
323
+ if _vfs_entry_kind(tree, path) != "folder":
324
+ return JSONResponse({"error": "Not a folder or not found."}, status_code=400)
325
+ vfs_set_tree(user_id, tree_remove_path(tree, path))
326
+ safe_prefix = path.rstrip("/").replace("\\", "/")
327
+
328
+ def path_prefix_match(p):
329
+ np = p.replace("\\", "/")
330
+ return np == safe_prefix or np.startswith(safe_prefix + "/")
331
+
332
+ user_document_delete_many(user_id, path_filter=path_prefix_match)
333
+ try:
334
+ col = get_user_collection(user_id)
335
+ res = col.get(include=["metadatas"])
336
+ ids_to_drop = []
337
+ for i, meta in enumerate(res.get("metadatas") or []):
338
+ p = (meta or {}).get("path") or (meta or {}).get("source_path") or ""
339
+ p = p.replace("\\", "/")
340
+ if p == safe_prefix or p.startswith(safe_prefix + "/"):
341
+ ids_to_drop.append(res["ids"][i])
342
+ if ids_to_drop:
343
+ col.delete(ids=ids_to_drop)
344
+ except Exception:
345
+ pass
346
+ delete_keys_for_prefix(user_id, path)
347
+ return JSONResponse({"message": "Folder deleted."})
348
+ return JSONResponse({"error": "Invalid kind. Use 'file' or 'folder'."}, status_code=400)
349
+
350
+
351
+ @app.post("/move_path")
352
+ def move_path(
353
+ from_path: str = Form(...),
354
+ to_folder: str = Form(""),
355
+ effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
356
+ ):
357
+ """Move a file or folder in the virtual tree and update Chroma paths."""
358
+ user_id, _ = effective
359
+ from_path = _strip_storage_path(from_path)
360
+ to_folder = _strip_storage_path(to_folder)
361
+ if ".." in from_path or ".." in to_folder:
362
+ return JSONResponse({"error": "Invalid path."}, status_code=400)
363
+ tree = _get_vfs_tree_clean(user_id)
364
+ kind = _vfs_entry_kind(tree, from_path)
365
+ if not kind:
366
+ return JSONResponse({"error": "Path not found."}, status_code=400)
367
+ name = os.path.basename(from_path.replace("\\", "/"))
368
+ dest_rel = (os.path.join(to_folder, name).replace("\\", "/") if to_folder else name).replace("\\", "/")
369
+ if dest_rel == from_path.replace("\\", "/"):
370
+ return JSONResponse({"message": "Already there.", "path": dest_rel})
371
+
372
+ if _path_exists_in_vfs(tree, dest_rel):
373
+ return JSONResponse({"error": f"'{name}' already exists in destination."}, status_code=400)
374
+
375
+ new_tree = tree_move_path(tree, from_path, to_folder)
376
+ vfs_set_tree(user_id, new_tree)
377
+
378
+ full_dest = dest_rel
379
+ was_file = kind == "file"
380
+ if was_file:
381
+ stem, extp = os.path.splitext(from_path)
382
+ chunks_relocate_path(user_id, from_path, full_dest)
383
+ if extp:
384
+ chunks_relocate_path(
385
+ user_id,
386
+ stem + ".txt",
387
+ os.path.splitext(full_dest)[0] + ".txt",
388
+ )
389
+ user_document_rename_path(user_id, from_path, full_dest)
390
+ if extp:
391
+ user_document_rename_path(
392
+ user_id,
393
+ stem + ".txt",
394
+ os.path.splitext(full_dest)[0] + ".txt",
395
+ )
396
+ file_meta_rename_path(user_id, from_path, full_dest)
397
+ if extp:
398
+ file_meta_rename_path(user_id, stem + ".txt", os.path.splitext(full_dest)[0] + ".txt")
399
+ else:
400
+ old_prefix = from_path.rstrip("/").replace("\\", "/")
401
+ new_prefix = full_dest.rstrip("/").replace("\\", "/")
402
+ chunks_relocate_folder_prefix(user_id, old_prefix, new_prefix)
403
+ user_documents_relocate_prefix(user_id, old_prefix, new_prefix)
404
+ file_meta_relocate_prefix(user_id, old_prefix, new_prefix)
405
+
406
+ return JSONResponse({"message": "Moved.", "path": dest_rel})
407
+
408
+
409
+ # ---------- Note operations (VFS + Chroma for signed-in and guest; guest user_id is guest_<uuid>) ----------
410
+ @app.post("/create_folder")
411
+ def create_folder(
412
+ path: str = Form(""),
413
+ name: str = Form(...),
414
+ effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
415
+ ):
416
+ user_id, _ = effective
417
+ path = _strip_storage_path(path)
418
+ name = (name or "").strip().replace("\\", "/").strip("/")
419
+ if not name or ".." in name or "/" in name:
420
+ return JSONResponse({"error": "Invalid folder name."}, status_code=400)
421
+ tree = _get_vfs_tree_clean(user_id)
422
+ if path and not tree_has_folder(tree, path):
423
+ return JSONResponse({"error": f"Folder '{path}' does not exist."}, status_code=400)
424
+ vfs_set_tree(user_id, tree_add_folder(tree, path, name))
425
+ rel = f"{path}/{name}".replace("//", "/").strip("/") if path else name
426
+ return JSONResponse({"message": f"Folder '{name}' created.", "path": rel})
427
+
428
+
429
+ @app.post("/create_file")
430
+ def create_file(
431
+ path: str = Form(""),
432
+ name: str = Form(...),
433
+ effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
434
+ ):
435
+ user_id, _ = effective
436
+ path = _strip_storage_path(path)
437
+ if path and ".." in path:
438
+ return JSONResponse({"error": "Invalid path."}, status_code=400)
439
+ tree = _get_vfs_tree_clean(user_id)
440
+ if path and not tree_has_folder(tree, path):
441
+ return JSONResponse({"error": f"Folder '{path}' does not exist."}, status_code=400)
442
+ filename = name if "." in name else f"{name}.txt"
443
+ if "/" in filename.replace("\\", "/") or ".." in filename:
444
+ return JSONResponse({"error": "Invalid file name."}, status_code=400)
445
+ vfs_set_tree(user_id, tree_add_file(tree, path, filename))
446
+ rel_path = f"{path}/{filename}".replace("//", "/").strip("/") if path else filename
447
+ user_document_upsert(user_id, rel_path, "", filename)
448
+ return JSONResponse({"message": f"File '{filename}' created.", "path": rel_path})
449
+
450
+
451
+ def _safe_user_document_upsert(user_id: str, path: str, content: str, original_filename: str) -> str | None:
452
+ """Best-effort cache write; should not block ingestion/query pipeline."""
453
+ try:
454
+ user_document_upsert(user_id, path, content, original_filename)
455
+ return None
456
+ except Exception as e:
457
+ return f"user_documents cache write skipped: {str(e)}"
458
+
459
+
460
+ @app.post("/upload_note")
461
+ def upload_note(
462
+ path: str = Form(""),
463
+ file: UploadFile = File(...),
464
+ effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
465
+ ):
466
+ user_id, _ = effective
467
+ path = _strip_storage_path(path)
468
+ if path and ".." in path:
469
+ return JSONResponse({"error": "Invalid path."}, status_code=400)
470
+ tree = _get_vfs_tree_clean(user_id)
471
+ if path and not tree_has_folder(tree, path):
472
+ return JSONResponse({"error": f"Folder '{path}' does not exist."}, status_code=400)
473
+
474
+ raw_name = (file.filename or "upload").replace("\\", "/").split("/")[-1]
475
+ if ".." in raw_name or not raw_name.strip():
476
+ return JSONResponse({"error": "Invalid file name."}, status_code=400)
477
+
478
+ file_content = file.file.read()
479
+ rel_path = _strip_storage_path(
480
+ (os.path.join(path, raw_name) if path else raw_name).replace("\\", "/"),
481
+ )
482
+ vfs_set_tree(user_id, tree_add_file(tree, path, raw_name))
483
+
484
+ is_pdf = raw_name.lower().endswith(".pdf")
485
+ ext = os.path.splitext(raw_name)[1].lower()
486
+ is_image = ext in (".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".gif", ".webp")
487
+
488
+ try:
489
+ warnings: list[str] = []
490
+ if is_pdf:
491
+ text, v_err = llm_pipeline.transcribe_document_bytes(file_content, "application/pdf")
492
+ if not (text or "").strip():
493
+ from backend.extract_api import extract_text_from_pdf_bytes
494
+ text = extract_text_from_pdf_bytes(file_content)
495
+ v_err = v_err or "used_pdf_parser_fallback"
496
+ rel_path_txt = rel_path.replace(os.path.splitext(rel_path)[1], ".txt")
497
+ w = _safe_user_document_upsert(user_id, rel_path_txt, text, raw_name)
498
+ if w:
499
+ warnings.append(w)
500
+ ingest_result = ingest_text_for_path(user_id, rel_path, raw_name, text or "")
501
+ return JSONResponse({
502
+ "message": f"File '{raw_name}' uploaded and processed successfully.",
503
+ "path": rel_path,
504
+ "vision_note": v_err,
505
+ "ingestion": ingest_result,
506
+ "warnings": warnings,
507
+ })
508
+ if is_image:
509
+ mime = {
510
+ ".jpg": "image/jpeg",
511
+ ".jpeg": "image/jpeg",
512
+ ".png": "image/png",
513
+ ".webp": "image/webp",
514
+ ".gif": "image/gif",
515
+ ".bmp": "image/bmp",
516
+ ".tiff": "image/tiff",
517
+ }.get(ext, "image/jpeg")
518
+ text, v_err = llm_pipeline.transcribe_handwritten_image(file_content, mime)
519
+ if not (text or "").strip():
520
+ from backend.extract_api import extract_text_from_image_bytes
521
+
522
+ text = extract_text_from_image_bytes(file_content)
523
+ v_err = v_err or "used_tesseract_fallback"
524
+ base_name = os.path.splitext(raw_name)[0] + ".txt"
525
+ rel_txt = (os.path.join(path, base_name) if path else base_name).replace("\\", "/")
526
+ w = _safe_user_document_upsert(user_id, rel_txt, text or "", raw_name)
527
+ if w:
528
+ warnings.append(w)
529
+ ingest_result = ingest_text_for_path(user_id, rel_txt, raw_name, text or "")
530
+ return JSONResponse({
531
+ "message": f"File '{raw_name}' uploaded and processed successfully.",
532
+ "path": rel_path,
533
+ "vision_note": v_err,
534
+ "ingestion": ingest_result,
535
+ "warnings": warnings,
536
+ })
537
+ if not is_pdf and not is_image:
538
+ text_plain = ""
539
+ low = raw_name.lower()
540
+ if low.endswith((".txt", ".md", ".csv", ".json", ".log")):
541
+ try:
542
+ text_plain = file_content.decode("utf-8")
543
+ except UnicodeDecodeError:
544
+ text_plain = file_content.decode("utf-8", errors="replace")
545
+ if (text_plain or "").strip():
546
+ w = _safe_user_document_upsert(user_id, rel_path, text_plain, raw_name)
547
+ if w:
548
+ warnings.append(w)
549
+ ingest_result = ingest_text_for_path(user_id, rel_path, raw_name, text_plain)
550
+ return JSONResponse({
551
+ "message": f"File '{raw_name}' uploaded and processed successfully.",
552
+ "path": rel_path,
553
+ "ingestion": ingest_result,
554
+ "warnings": warnings,
555
+ })
556
+ return JSONResponse({
557
+ "message": f"File '{raw_name}' recorded (no server-side binary stored).",
558
+ "path": rel_path,
559
+ "warnings": warnings,
560
+ })
561
+ except Exception as e:
562
+ return JSONResponse({
563
+ "message": f"File '{raw_name}' recorded but processing failed: {str(e)}",
564
+ "path": rel_path,
565
+ }, status_code=500)
566
+
567
+
568
+ @app.post("/chat/upload_ephemeral")
569
+ def chat_upload_ephemeral(
570
+ chat_session_id: str = Form(...),
571
+ file: UploadFile = File(...),
572
+ effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
573
+ ):
574
+ user_id, _ = effective
575
+ sid = (chat_session_id or "").strip()
576
+ if not sid:
577
+ return JSONResponse({"error": "chat_session_id is required."}, status_code=400)
578
+ raw_name = (file.filename or "upload").replace("\\", "/").split("/")[-1]
579
+ if ".." in raw_name or not raw_name.strip():
580
+ return JSONResponse({"error": "Invalid file name."}, status_code=400)
581
+ data = file.file.read()
582
+ ext = os.path.splitext(raw_name)[1].lower()
583
+ is_pdf = ext == ".pdf"
584
+ is_image = ext in (".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".gif", ".webp")
585
+ text = ""
586
+ source = ""
587
+ if is_pdf:
588
+ text, source = llm_pipeline.transcribe_document_bytes(data, "application/pdf")
589
+ if not (text or "").strip():
590
+ from backend.extract_api import extract_text_from_pdf_bytes
591
+ text = extract_text_from_pdf_bytes(data)
592
+ source = source or "used_pdf_parser_fallback"
593
+ elif is_image:
594
+ mime = {
595
+ ".jpg": "image/jpeg",
596
+ ".jpeg": "image/jpeg",
597
+ ".png": "image/png",
598
+ ".webp": "image/webp",
599
+ ".gif": "image/gif",
600
+ ".bmp": "image/bmp",
601
+ ".tiff": "image/tiff",
602
+ }.get(ext, "image/jpeg")
603
+ text, source = llm_pipeline.transcribe_handwritten_image(data, mime)
604
+ if not (text or "").strip():
605
+ from backend.extract_api import extract_text_from_image_bytes
606
+ text = extract_text_from_image_bytes(data)
607
+ source = source or "used_tesseract_fallback"
608
+ else:
609
+ if raw_name.lower().endswith((".txt", ".md", ".csv", ".json", ".log")):
610
+ try:
611
+ text = data.decode("utf-8")
612
+ except UnicodeDecodeError:
613
+ text = data.decode("utf-8", errors="replace")
614
+ source = "plain_text"
615
+ if not (text or "").strip():
616
+ return JSONResponse({"error": "No extractable text found in this file."}, status_code=400)
617
+ _chat_cache_add(
618
+ user_id,
619
+ sid,
620
+ {
621
+ "name": raw_name,
622
+ "text": (text or "").strip()[:120000],
623
+ "source": source or "",
624
+ "uploaded_at": datetime.now().isoformat(),
625
+ },
626
+ )
627
+ return JSONResponse(
628
+ {
629
+ "message": f"Cached '{raw_name}' for this chat session.",
630
+ "chat_session_id": sid,
631
+ "cached_files_count": len(_chat_cache_items(user_id, sid)),
632
+ "text_chars": len((text or "").strip()),
633
+ "extractor_note": source or "",
634
+ }
635
+ )
636
+
637
+
638
+ @app.post("/chat/session/clear")
639
+ def clear_chat_session_cache(
640
+ chat_session_id: str = Form(...),
641
+ effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
642
+ ):
643
+ user_id, _ = effective
644
+ sid = (chat_session_id or "").strip()
645
+ if not sid:
646
+ return JSONResponse({"error": "chat_session_id is required."}, status_code=400)
647
+ deleted = _chat_cache_clear(user_id, sid)
648
+ return JSONResponse({"message": "Chat cache cleared.", "deleted_files": deleted})
649
+
650
+
651
+ @app.delete("/notes")
652
+ def delete_notes(
653
+ file: str | None = None,
654
+ files: str | None = None,
655
+ effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
656
+ ):
657
+ """
658
+ Delete the authenticated user's note chunks from ChromaDB.
659
+ - No query params: delete entire collection (user_{user_id}_notes).
660
+ - file=<path>: delete only chunks for that path.
661
+ - files=<path1>,<path2>: delete only chunks for those paths.
662
+ """
663
+ user_id, _ = effective
664
+ if file:
665
+ paths = [p.strip() for p in [file] if p and p.strip()]
666
+ elif files:
667
+ paths = [p.strip() for p in files.split(",") if p and p.strip()]
668
+ else:
669
+ paths = None
670
+ if paths is not None:
671
+ if not paths:
672
+ return JSONResponse({"error": "No paths provided."}, status_code=400)
673
+ for p in paths:
674
+ if ".." in p or p.startswith("/"):
675
+ return JSONResponse({"error": "Invalid path."}, status_code=400)
676
+ paths = [_strip_storage_path(p) for p in paths]
677
+ deleted = delete_user_notes_by_paths(user_id, paths)
678
+ return JSONResponse({"message": f"Deleted {deleted} chunk(s) for the given file(s).", "deleted_count": deleted})
679
+ deleted_notes = delete_user_notes_collection(user_id)
680
+ deleted_vfs = delete_user_vfs_collection(user_id)
681
+ user_document_delete_many(user_id, path_filter=None)
682
+ return JSONResponse({
683
+ "message": "All notes data deleted." if deleted_notes else "No notes collection found.",
684
+ "deleted_notes": deleted_notes,
685
+ "deleted_vfs": deleted_vfs,
686
+ })
687
+
688
+
689
+ @app.get("/list_tree")
690
+ def list_tree(effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None):
691
+ user_id, _ = effective
692
+ return {"tree": _get_vfs_tree_clean(user_id)}
693
+
694
+
695
+
696
+
697
+ @app.post("/query_folder")
698
+ def query_notes(
699
+ subject: str = Form(""),
700
+ courses: str = Form(""),
701
+ query: str = Form(...),
702
+ highlight: str = Form(""),
703
+ opened_file_path: str = Form(""),
704
+ course_path: str = Form(""),
705
+ include_course_context: bool = Form(True),
706
+ chat_session_id: str = Form(""),
707
+ use_course_notes: bool = Form(False),
708
+ effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
709
+ ):
710
+ user_id, _ = effective
711
+ q = (query or "").strip()
712
+ if not q:
713
+ return JSONResponse({"error": "Query is empty.", "answer": "", "source_documents": []}, status_code=400)
714
+ tree = _get_vfs_tree_clean(user_id)
715
+ all_paths = [p.replace("\\", "/") for p in flatten_file_paths(tree)]
716
+ all_set = set(all_paths)
717
+ opened = _strip_storage_path(opened_file_path or "")
718
+ course = _strip_storage_path(course_path or "")
719
+ if not course and opened:
720
+ course = opened.split("/", 1)[0] if "/" in opened else opened
721
+ if course and "/" in course:
722
+ course = course.split("/", 1)[0]
723
+ ephemeral = _chat_cache_items(user_id, chat_session_id)
724
+
725
+ hl = (highlight or "").strip()
726
+ full_q = f'Regarding this selection:\n"""{hl}"""\n\n{q}' if hl else q
727
+ try:
728
+ col = get_user_collection(user_id)
729
+ embed = _get_query_embedder()
730
+ q_emb = embed.encode([full_q]).tolist()[0]
731
+
732
+ def _cos(a: list[float], b: list[float]) -> float:
733
+ dot = sum((x * y) for x, y in zip(a, b))
734
+ na = (sum((x * x) for x in a) or 1e-9) ** 0.5
735
+ nb = (sum((y * y) for y in b) or 1e-9) ** 0.5
736
+ return float(dot / (na * nb))
737
+
738
+ def _split_text(t: str, size: int = 900, overlap: int = 120) -> list[str]:
739
+ tx = (t or "").strip()
740
+ if not tx:
741
+ return []
742
+ out: list[str] = []
743
+ i = 0
744
+ n = len(tx)
745
+ while i < n:
746
+ out.append(tx[i : i + size])
747
+ i += max(1, size - overlap)
748
+ return out
749
+
750
+ def _query_path_docs(path: str, n_results: int = 5) -> list[dict]:
751
+ res = col.query(
752
+ query_embeddings=[q_emb],
753
+ n_results=n_results,
754
+ where={"path": path},
755
+ include=["documents", "metadatas", "distances"],
756
+ )
757
+ ids = (res.get("ids") or [[]])[0] if isinstance(res.get("ids"), list) else []
758
+ docs = (res.get("documents") or [[]])[0] if isinstance(res.get("documents"), list) else []
759
+ metas = (res.get("metadatas") or [[]])[0] if isinstance(res.get("metadatas"), list) else []
760
+ dists = (res.get("distances") or [[]])[0] if isinstance(res.get("distances"), list) else []
761
+ out = []
762
+ for i, cid in enumerate(ids):
763
+ content = (docs[i] if i < len(docs) else "") or ""
764
+ if not content.strip():
765
+ continue
766
+ md = metas[i] if i < len(metas) and isinstance(metas[i], dict) else {}
767
+ dist = float(dists[i]) if i < len(dists) and dists[i] is not None else 2.0
768
+ score = 1.0 - dist
769
+ out.append({"id": cid, "content": content, "metadata": md, "_score": score})
770
+ out.sort(key=lambda d: d.get("_score", -9), reverse=True)
771
+ return out
772
+
773
+ # Stage 1: ephemeral chat uploads (highest priority)
774
+ eph_docs: list[dict] = []
775
+ for i, it in enumerate(ephemeral):
776
+ et = str((it or {}).get("text") or "").strip()
777
+ if not et:
778
+ continue
779
+ chunks = _split_text(et, size=900, overlap=140)[:24]
780
+ if not chunks:
781
+ continue
782
+ c_embs = embed.encode(chunks).tolist()
783
+ ranked = sorted(
784
+ [(_cos(q_emb, ce), ch) for ce, ch in zip(c_embs, chunks)],
785
+ key=lambda x: x[0],
786
+ reverse=True,
787
+ )[:3]
788
+ for j, (sc, ch) in enumerate(ranked):
789
+ eph_docs.append(
790
+ {
791
+ "id": f"ephemeral|{i}|{j}",
792
+ "content": ch,
793
+ "metadata": {
794
+ "path": f"[chat-upload] {(it or {}).get('name') or 'file'}",
795
+ "source_file": (it or {}).get("name") or "chat-upload",
796
+ "ephemeral_chat_upload": 1,
797
+ },
798
+ "_score": float(sc),
799
+ }
800
+ )
801
+ eph_docs.sort(key=lambda d: d.get("_score", -9), reverse=True)
802
+ eph_best = eph_docs[0]["_score"] if eph_docs else -1.0
803
+
804
+ # Stage 2: opened file
805
+ open_docs: list[dict] = []
806
+ if opened and opened in all_set:
807
+ open_docs = _query_path_docs(opened, n_results=6)
808
+ open_best = open_docs[0]["_score"] if open_docs else -1.0
809
+
810
+ # Stage 3: same course files (excluding opened)
811
+ course_docs: list[dict] = []
812
+ if include_course_context and course:
813
+ prefix = f"{course}/"
814
+ course_paths = [p for p in all_paths if p != opened and p.startswith(prefix)]
815
+ for p in course_paths[:18]:
816
+ course_docs.extend(_query_path_docs(p, n_results=2))
817
+ course_docs.sort(key=lambda d: d.get("_score", -9), reverse=True)
818
+ course_best = course_docs[0]["_score"] if course_docs else -1.0
819
+
820
+ # Sequence policy:
821
+ # 1) use ephemeral if relevant enough
822
+ # 2) otherwise opened file
823
+ # 3) otherwise same-course files
824
+ selected: list[dict] = []
825
+ stage = "ephemeral"
826
+ if eph_docs and eph_best >= 0.32:
827
+ selected = eph_docs[:8]
828
+ stage = "ephemeral"
829
+ elif open_docs and open_best >= 0.05:
830
+ selected = open_docs[:8]
831
+ stage = "opened"
832
+ elif course_docs and course_best >= 0.02:
833
+ selected = course_docs[:8]
834
+ stage = "course"
835
+ else:
836
+ # Smart fallback: best available source by embedding score.
837
+ cands = [
838
+ ("ephemeral", eph_best, eph_docs),
839
+ ("opened", open_best, open_docs),
840
+ ("course", course_best, course_docs),
841
+ ]
842
+ cands.sort(key=lambda x: x[1], reverse=True)
843
+ stage, _best, dd = cands[0]
844
+ selected = (dd or [])[:8]
845
+
846
+ if not selected:
847
+ return JSONResponse(
848
+ {
849
+ "error": "No relevant text found in chat uploads, open file, or course notes.",
850
+ "query": q,
851
+ "answer": "",
852
+ "source_documents": [],
853
+ },
854
+ status_code=400,
855
+ )
856
+
857
+ context = "\n\n".join(
858
+ [
859
+ f"[{(d.get('metadata') or {}).get('path') or 'chunk'}]\n{(d.get('content') or '')[:1200]}"
860
+ for d in selected
861
+ if (d.get("content") or "").strip()
862
+ ]
863
+ )
864
+ answer, err = llm_pipeline.sarvam_rag_answer(full_q, context)
865
+ if err:
866
+ return JSONResponse(
867
+ {
868
+ "error": err,
869
+ "query": q,
870
+ "answer": "",
871
+ "source_documents": [],
872
+ },
873
+ status_code=503,
874
+ )
875
+ docs_out = [{k: v for k, v in d.items() if k != "_score"} for d in selected]
876
+ return JSONResponse(
877
+ {
878
+ "query": q,
879
+ "answer": answer or "",
880
+ "source_documents": docs_out,
881
+ "grounded_on_path": opened,
882
+ "ephemeral_files_used": len(ephemeral),
883
+ "selection_stage": stage,
884
+ "score_ephemeral_best": round(float(eph_best), 4),
885
+ "score_opened_best": round(float(open_best), 4),
886
+ "score_course_best": round(float(course_best), 4),
887
+ }
888
+ )
889
+ except Exception as e:
890
+ return JSONResponse(
891
+ {
892
+ "error": f"Query failed: {str(e)}",
893
+ "query": q,
894
+ "answer": "",
895
+ "source_documents": [],
896
+ },
897
+ status_code=500,
898
+ )
899
+
900
+
901
+ @app.get("/file_meta")
902
+ def get_file_meta_route(
903
+ effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
904
+ ):
905
+ user_id, _ = effective
906
+ return {"meta": load_file_meta(user_id)}
907
+
908
+
909
+ @app.post("/file_meta")
910
+ def post_file_meta(
911
+ path: str = Form(...),
912
+ is_primary_authority: str = Form("false"),
913
+ doc_type: str = Form(""),
914
+ related_paths: str = Form(""),
915
+ effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
916
+ ):
917
+ user_id, _ = effective
918
+ path = _strip_storage_path(path)
919
+ primary = str(is_primary_authority).lower() in ("1", "true", "yes", "on")
920
+ rel_list = [
921
+ _strip_storage_path(x.strip().replace("\\", "/"))
922
+ for x in related_paths.split(",")
923
+ if x.strip()
924
+ ]
925
+ entry = set_entry(
926
+ user_id,
927
+ path,
928
+ is_primary_authority=primary,
929
+ doc_type=(doc_type or "other"),
930
+ related_paths=rel_list,
931
+ )
932
+ n = refresh_metadata_for_paths(user_id, chunk_paths_for_file(path))
933
+ return JSONResponse({"path": path, "entry": entry, "chunks_updated": n})
934
+
935
+
936
+ def _doc_text_for_virtual_path(user_id: str, rel_path: str) -> str:
937
+ """Resolve extracted/stored text for a virtual file path."""
938
+ p = _strip_storage_path(rel_path or "")
939
+ if not p:
940
+ return ""
941
+ direct = user_document_get_content(user_id, p)
942
+ if (direct or "").strip():
943
+ return (direct or "").strip()
944
+ stem, ext = os.path.splitext(p)
945
+ if ext.lower() != ".txt":
946
+ txt = user_document_get_content(user_id, stem + ".txt")
947
+ if (txt or "").strip():
948
+ return (txt or "").strip()
949
+ return ""
950
+
951
+
952
+ def _study_text_for_path(user_id: str, rel_path: str) -> str:
953
+ """Prefer Chroma chunk text (same as RAG), fall back to user_documents."""
954
+ p = _strip_storage_path(rel_path or "")
955
+ if not p:
956
+ return ""
957
+ chunk = (user_notes_concat_text_for_path(user_id, p) or "").strip()
958
+ if chunk:
959
+ return chunk
960
+ return (_doc_text_for_virtual_path(user_id, p) or "").strip()
961
+
962
+
963
+ def _build_study_scope_context(
964
+ user_id: str,
965
+ opened_file_path: str,
966
+ course_path: str,
967
+ focus_query: str,
968
+ include_course_context: bool,
969
+ ) -> tuple[str | None, str | None]:
970
+ """Return context strictly from opened file and optionally same course folder."""
971
+ open_rel = _strip_storage_path(opened_file_path or "")
972
+ if not open_rel:
973
+ return None, "Open a file first. Study generation uses the active file context."
974
+
975
+ tree = _get_vfs_tree_clean(user_id)
976
+ all_paths = [p.replace("\\", "/") for p in flatten_file_paths(tree)]
977
+ all_set = set(all_paths)
978
+ if open_rel not in all_set:
979
+ return None, f"Active file '{open_rel}' was not found in your notes."
980
+
981
+ root_course = _strip_storage_path(course_path or "")
982
+ if not root_course:
983
+ root_course = open_rel.split("/", 1)[0] if "/" in open_rel else open_rel
984
+ # Root course is only a top-level folder scope, never a file path.
985
+ root_course = root_course.split("/", 1)[0] if root_course else ""
986
+
987
+ open_text = (_study_text_for_path(user_id, open_rel) or "").strip()
988
+ if not open_text:
989
+ return None, (
990
+ f"No extracted text or chunks found for '{open_rel}'. "
991
+ "Re-upload the file or wait for ingestion to finish."
992
+ )
993
+
994
+ focus = (focus_query or "").strip() or "key ideas for exam"
995
+ parts = [
996
+ f"Focus: {focus}",
997
+ f"Active course folder: {root_course or '(root)'}",
998
+ f"Primary file: {open_rel}",
999
+ "",
1000
+ "--- PRIMARY FILE CONTENT ---",
1001
+ open_text[:35000],
1002
+ ]
1003
+
1004
+ if include_course_context and root_course:
1005
+ prefix = root_course + "/"
1006
+ extra_paths = [p for p in all_paths if p != open_rel and (p == root_course or p.startswith(prefix))]
1007
+ if extra_paths:
1008
+ budget = 25000
1009
+ extras: list[str] = []
1010
+ for p in extra_paths:
1011
+ if budget <= 0:
1012
+ break
1013
+ t = _study_text_for_path(user_id, p)
1014
+ if not t:
1015
+ continue
1016
+ chunk = t[: min(len(t), 3500, budget)]
1017
+ if not chunk.strip():
1018
+ continue
1019
+ extras.append(f"--- COURSE SUPPORTING FILE: {p} ---\n{chunk}")
1020
+ budget -= len(chunk)
1021
+ if extras:
1022
+ parts.append("")
1023
+ parts.append("--- OPTIONAL SAME-COURSE SUPPORT ---")
1024
+ parts.append("\n\n".join(extras))
1025
+
1026
+ return "\n".join(parts)[:60000], None
1027
+
1028
+
1029
+ @app.post("/study/generate")
1030
+ def study_generate(
1031
+ task: str = Form("flashcards"),
1032
+ count: int = Form(5),
1033
+ courses: str = Form(""),
1034
+ focus_query: str = Form("key ideas for exam"),
1035
+ opened_file_path: str = Form(""),
1036
+ course_path: str = Form(""),
1037
+ include_course_context: bool = Form(True),
1038
+ effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
1039
+ ):
1040
+ _uid, _ = effective
1041
+ course_list = [c.strip() for c in courses.split(",") if c.strip()]
1042
+ focus = (focus_query or "").strip() or "key ideas for exam"
1043
+ scope = ", ".join(course_list) if course_list else "general"
1044
+ ctx, cerr = _build_study_scope_context(
1045
+ _uid,
1046
+ opened_file_path,
1047
+ course_path,
1048
+ focus,
1049
+ include_course_context,
1050
+ )
1051
+ if cerr:
1052
+ return JSONResponse({"error": cerr, "scope": scope}, status_code=400)
1053
+ data, err = llm_pipeline.cheap_study_json(ctx, task, max(1, min(count, 30)))
1054
+ if err:
1055
+ return JSONResponse({"error": err}, status_code=503)
1056
+ return JSONResponse(
1057
+ {
1058
+ "task": task,
1059
+ "items": data,
1060
+ "grounded_on_path": _strip_storage_path(opened_file_path or ""),
1061
+ "context_chars": len(ctx or ""),
1062
+ }
1063
+ )
1064
+
1065
+
1066
+ @app.post("/study/mindmap")
1067
+ def study_mindmap(
1068
+ courses: str = Form(""),
1069
+ focus_query: str = Form("main concepts"),
1070
+ opened_file_path: str = Form(""),
1071
+ course_path: str = Form(""),
1072
+ include_course_context: bool = Form(True),
1073
+ effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
1074
+ ):
1075
+ _uid, _ = effective
1076
+ course_list = [c.strip() for c in courses.split(",") if c.strip()]
1077
+ focus = (focus_query or "").strip() or "main concepts"
1078
+ scope = ", ".join(course_list) if course_list else "general"
1079
+ ctx, cerr = _build_study_scope_context(
1080
+ _uid,
1081
+ opened_file_path,
1082
+ course_path,
1083
+ focus,
1084
+ include_course_context,
1085
+ )
1086
+ if cerr:
1087
+ return JSONResponse({"error": cerr, "scope": scope}, status_code=400)
1088
+ data, err = llm_pipeline.mind_map_json(ctx)
1089
+ if err:
1090
+ return JSONResponse({"error": err}, status_code=503)
1091
+ return JSONResponse(
1092
+ {
1093
+ "graph": data,
1094
+ "grounded_on_path": _strip_storage_path(opened_file_path or ""),
1095
+ "context_chars": len(ctx or ""),
1096
+ }
1097
+ )
1098
+
1099
+
1100
+ @app.get("/integrations/onenote/status")
1101
+ def onenote_status(
1102
+ effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
1103
+ ):
1104
+ user_id, is_guest = effective
1105
+ connected = False
1106
+ if not is_guest:
1107
+ connected = bool(onenote_token_get(user_id))
1108
+ return {
1109
+ "configured": onenote_sync.is_configured(),
1110
+ "connected": connected,
1111
+ "requires_sign_in": is_guest,
1112
+ "redirect_uri": onenote_sync.redirect_uri(),
1113
+ }
1114
+
1115
+
1116
+ @app.get("/integrations/onenote/auth_url")
1117
+ def onenote_auth_url(
1118
+ effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
1119
+ ):
1120
+ user_id = _require_signed_in(effective)
1121
+ if not onenote_sync.is_configured():
1122
+ return JSONResponse(
1123
+ {"error": "Microsoft OAuth is not configured on server."},
1124
+ status_code=503,
1125
+ )
1126
+ state = str(uuid.uuid4())
1127
+ onenote_oauth_state_create(user_id, state, int(time.time()) + 600)
1128
+ return {"auth_url": onenote_sync.build_auth_url(state), "state": state}
1129
+
1130
+
1131
+ @app.get("/integrations/onenote/callback")
1132
+ def onenote_callback(code: str = "", state: str = "", error: str = "", error_description: str = ""):
1133
+ if error:
1134
+ msg = error_description or error
1135
+ html = (
1136
+ "<html><body><h3>OneNote connect failed</h3>"
1137
+ f"<p>{msg}</p><p>You can close this tab.</p></body></html>"
1138
+ )
1139
+ return HTMLResponse(content=html, status_code=400)
1140
+ if not code or not state:
1141
+ return HTMLResponse(
1142
+ content="<html><body><h3>Missing OAuth parameters.</h3><p>Close this tab.</p></body></html>",
1143
+ status_code=400,
1144
+ )
1145
+ user_id = onenote_oauth_state_pop_user_id(state)
1146
+ if not user_id:
1147
+ return HTMLResponse(
1148
+ content="<html><body><h3>OAuth state is invalid or expired.</h3><p>Restart connection.</p></body></html>",
1149
+ status_code=400,
1150
+ )
1151
+ try:
1152
+ token_payload = onenote_sync.exchange_code_for_token(code)
1153
+ onenote_token_upsert(user_id, token_payload)
1154
+ return HTMLResponse(
1155
+ content="<html><body><h3>OneNote connected successfully.</h3><p>You can close this tab and return to NoteScanner.</p></body></html>"
1156
+ )
1157
+ except Exception as e:
1158
+ return HTMLResponse(
1159
+ content=f"<html><body><h3>Token exchange failed.</h3><p>{str(e)}</p><p>Close this tab.</p></body></html>",
1160
+ status_code=500,
1161
+ )
1162
+
1163
+
1164
+ @app.post("/integrations/onenote/sync")
1165
+ def onenote_sync_route(
1166
+ max_pages: int = Form(25),
1167
+ effective: Annotated[tuple[str, bool], Depends(get_effective_user_dep)] = None,
1168
+ ):
1169
+ user_id = _require_signed_in(effective)
1170
+ if not onenote_sync.is_configured():
1171
+ return JSONResponse({"error": "Microsoft OAuth is not configured on server."}, status_code=503)
1172
+ try:
1173
+ out = onenote_sync.sync_onenote_pages_to_ingest(user_id, max_pages=max_pages)
1174
+ return JSONResponse({"message": "OneNote sync complete.", **out})
1175
+ except Exception as e:
1176
+ return JSONResponse({"error": str(e)}, status_code=500)
1177
+
1178
+
1179
+ if __name__ == "__main__":
1180
+ import uvicorn
1181
+ uvicorn.run(app, host="0.0.0.0", port=8000)
backend/auth.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Simple session-based auth (no JWT) and password hashing for NoteScanner."""
2
+ from fastapi import Request
3
+
4
+ from backend.chroma_store import session_create, session_get_user_id
5
+
6
+ # Re-export for callers that import from auth
7
+ from passlib.context import CryptContext
8
+
9
+ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
10
+
11
+ SESSION_HEADER = "X-Session-Id"
12
+ GUEST_HEADER = "X-Guest-Id"
13
+
14
+
15
+ def hash_password(password: str) -> str:
16
+ return pwd_context.hash(password)
17
+
18
+
19
+ def verify_password(plain: str, hashed: str) -> bool:
20
+ return pwd_context.verify(plain, hashed)
21
+
22
+
23
+ def create_session(user_id: str) -> str:
24
+ return session_create(user_id)
25
+
26
+
27
+ def get_user_id_from_session(session_id: str) -> str | None:
28
+ return session_get_user_id(session_id)
29
+
30
+
31
+ def get_effective_user(request: Request) -> tuple[str, bool]:
32
+ """
33
+ Returns (effective_user_id, is_guest).
34
+ - If X-Session-Id is valid -> (user_id, False).
35
+ - Else if X-Guest-Id present -> ("guest_<id>", True).
36
+ - Else raises ValueError (caller should return 400; client must call GET /guest_id first).
37
+ """
38
+ session_id = request.headers.get(SESSION_HEADER)
39
+ user_id = get_user_id_from_session(session_id)
40
+ if user_id:
41
+ return user_id, False
42
+ guest_id = request.headers.get(GUEST_HEADER)
43
+ if guest_id:
44
+ return f"guest_{guest_id}", True
45
+ raise ValueError("Missing X-Guest-Id. Call GET /guest_id first or sign in.")
backend/chroma_store.py ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Single-database store using ChromaDB for NoteScanner.
3
+
4
+ Stores:
5
+ - Users, sessions: metadata + dummy embeddings
6
+ - user_documents: full extracted text per logical path + metadata + 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
+
10
+ Connection:
11
+ - If CHROMA_API_KEY is set → Chroma Cloud (CHROMA_TENANT, CHROMA_DATABASE; optional CHROMA_HOST override via settings if supported)
12
+ - Else → self-hosted HttpClient (CHROMA_HOST, CHROMA_PORT, optional CHROMA_SSL=true)
13
+ """
14
+ import json
15
+ import os
16
+ import uuid
17
+ import time
18
+ import chromadb
19
+
20
+ EMBEDDING_DIM = 384 # all-MiniLM-L6-v2
21
+ USER_DOCUMENT_MAX_BYTES = int((os.getenv("USER_DOCUMENT_MAX_BYTES") or "12000").strip() or "12000")
22
+
23
+ _global_client = None
24
+
25
+
26
+ def _dummy_embedding():
27
+ return [0.0] * EMBEDDING_DIM
28
+
29
+
30
+ def get_global_client():
31
+ global _global_client
32
+ if _global_client is None:
33
+ api_key = (os.getenv("CHROMA_API_KEY") or "").strip()
34
+ if api_key:
35
+ tenant = (os.getenv("CHROMA_TENANT") or "").strip() or None
36
+ database = (os.getenv("CHROMA_DATABASE") or "").strip() or None
37
+ kwargs: dict = {"api_key": api_key}
38
+ if tenant:
39
+ kwargs["tenant"] = tenant
40
+ if database:
41
+ kwargs["database"] = database
42
+ _global_client = chromadb.CloudClient(**kwargs)
43
+ else:
44
+ host = (os.getenv("CHROMA_HOST") or "localhost").strip()
45
+ port_raw = (os.getenv("CHROMA_PORT") or "8100").strip()
46
+ try:
47
+ port = int(port_raw)
48
+ except ValueError:
49
+ port = 8100
50
+ ssl = (os.getenv("CHROMA_SSL") or "").lower() in ("1", "true", "yes")
51
+ _global_client = chromadb.HttpClient(host=host, port=port, ssl=ssl)
52
+ return _global_client
53
+
54
+
55
+ def _get_or_create_collection(name: str):
56
+ client = get_global_client()
57
+ try:
58
+ return client.get_collection(name=name)
59
+ except Exception:
60
+ return client.create_collection(name=name, metadata={"description": "NoteScanner"})
61
+
62
+
63
+ def get_user_collection(user_id: str):
64
+ """Get or create the per-user RAG collection for note chunks (user_{user_id}_notes)."""
65
+ name = f"user_{user_id}_notes"
66
+ return _get_or_create_collection(name)
67
+
68
+
69
+ def user_notes_concat_text_for_path(user_id: str, path: str) -> str:
70
+ """
71
+ Concatenate all chunk documents for a virtual file path (metadata.path from ingest).
72
+ PDFs/images are ingested under the original path (e.g. Maths/L3.1_Part1.pdf), not only user_documents.
73
+ """
74
+ p = (path or "").replace("\\", "/").strip()
75
+ if not p:
76
+ return ""
77
+ col = get_user_collection(user_id)
78
+ try:
79
+ res = col.get(where={"path": p}, include=["documents", "metadatas"])
80
+ except Exception:
81
+ return ""
82
+ docs = res.get("documents") or []
83
+ metas = res.get("metadatas") or []
84
+ if not docs:
85
+ return ""
86
+ pairs: list[tuple[int, str]] = []
87
+ for i, doc in enumerate(docs):
88
+ meta = metas[i] if i < len(metas) else {}
89
+ idx = i
90
+ if isinstance(meta, dict) and meta.get("chunk_index") is not None:
91
+ try:
92
+ idx = int(meta["chunk_index"])
93
+ except (TypeError, ValueError):
94
+ idx = i
95
+ text = (doc or "").strip()
96
+ if text:
97
+ pairs.append((idx, text))
98
+ pairs.sort(key=lambda x: x[0])
99
+ return "\n\n".join(t for _, t in pairs)
100
+
101
+
102
+ def delete_user_notes_collection(user_id: str) -> bool:
103
+ """Delete the entire per-user RAG collection. Returns True if deleted, False if it did not exist."""
104
+ client = get_global_client()
105
+ name = f"user_{user_id}_notes"
106
+ try:
107
+ client.delete_collection(name=name)
108
+ return True
109
+ except Exception:
110
+ return False
111
+
112
+
113
+ def get_user_vfs_collection(user_id: str):
114
+ """Virtual folder tree + file metadata (JSON documents). Binaries are not stored."""
115
+ name = f"user_{user_id}_vfs"
116
+ return _get_or_create_collection(name)
117
+
118
+
119
+ VFS_TREE_DOC_ID = "vfs_tree"
120
+ VFS_FILE_META_DOC_ID = "vfs_file_meta"
121
+
122
+
123
+ def vfs_get_tree(user_id: str) -> list:
124
+ col = get_user_vfs_collection(user_id)
125
+ try:
126
+ res = col.get(ids=[VFS_TREE_DOC_ID], include=["documents"])
127
+ if not res.get("ids"):
128
+ return []
129
+ raw = (res.get("documents") or [""])[0] or "[]"
130
+ data = json.loads(raw)
131
+ return data if isinstance(data, list) else []
132
+ except Exception:
133
+ return []
134
+
135
+
136
+ def vfs_set_tree(user_id: str, tree: list) -> None:
137
+ col = get_user_vfs_collection(user_id)
138
+ doc = json.dumps(tree, ensure_ascii=False)
139
+ try:
140
+ col.delete(ids=[VFS_TREE_DOC_ID])
141
+ except Exception:
142
+ pass
143
+ col.add(
144
+ ids=[VFS_TREE_DOC_ID],
145
+ documents=[doc],
146
+ embeddings=[_dummy_embedding()],
147
+ metadatas=[{"kind": "vfs_tree"}],
148
+ )
149
+
150
+
151
+ def vfs_get_file_meta_dict(user_id: str) -> dict:
152
+ col = get_user_vfs_collection(user_id)
153
+ try:
154
+ res = col.get(ids=[VFS_FILE_META_DOC_ID], include=["documents"])
155
+ if not res.get("ids"):
156
+ return {}
157
+ raw = (res.get("documents") or [""])[0] or "{}"
158
+ data = json.loads(raw)
159
+ return data if isinstance(data, dict) else {}
160
+ except Exception:
161
+ return {}
162
+
163
+
164
+ def vfs_set_file_meta_dict(user_id: str, meta: dict) -> None:
165
+ col = get_user_vfs_collection(user_id)
166
+ doc = json.dumps(meta, ensure_ascii=False)
167
+ try:
168
+ col.delete(ids=[VFS_FILE_META_DOC_ID])
169
+ except Exception:
170
+ pass
171
+ col.add(
172
+ ids=[VFS_FILE_META_DOC_ID],
173
+ documents=[doc],
174
+ embeddings=[_dummy_embedding()],
175
+ metadatas=[{"kind": "vfs_file_meta"}],
176
+ )
177
+
178
+
179
+ def delete_user_vfs_collection(user_id: str) -> bool:
180
+ client = get_global_client()
181
+ name = f"user_{user_id}_vfs"
182
+ try:
183
+ client.delete_collection(name=name)
184
+ return True
185
+ except Exception:
186
+ return False
187
+
188
+
189
+ def delete_user_notes_by_paths(user_id: str, paths: list[str]) -> int:
190
+ """Delete chunks whose metadata path is in paths. Returns number of ids deleted."""
191
+ if not paths:
192
+ return 0
193
+ col = get_user_collection(user_id)
194
+ ids_to_drop = []
195
+ for p in paths:
196
+ try:
197
+ res = col.get(where={"path": p}, include=[])
198
+ ids_to_drop.extend(res.get("ids") or [])
199
+ except Exception:
200
+ continue
201
+ if ids_to_drop:
202
+ col.delete(ids=ids_to_drop)
203
+ return len(ids_to_drop)
204
+
205
+
206
+ # ---------- Users ----------
207
+ def get_users_collection():
208
+ return _get_or_create_collection("users")
209
+
210
+
211
+ def user_exists_by_email(email: str) -> bool:
212
+ col = get_users_collection()
213
+ res = col.get(where={"email": email.lower()})
214
+ return len(res["ids"]) > 0
215
+
216
+
217
+ def user_create(email: str, hashed_password: str, name: str) -> str:
218
+ user_id = str(uuid.uuid4())
219
+ col = get_users_collection()
220
+ col.add(
221
+ ids=[user_id],
222
+ documents=[""],
223
+ metadatas=[{"email": email.lower(), "hashed_password": hashed_password, "name": name or email.split("@")[0]}],
224
+ embeddings=[_dummy_embedding()],
225
+ )
226
+ return user_id
227
+
228
+
229
+ def user_get_by_email(email: str) -> dict | None:
230
+ col = get_users_collection()
231
+ res = col.get(where={"email": email.lower()})
232
+ if not res["ids"]:
233
+ return None
234
+ return {
235
+ "user_id": res["ids"][0],
236
+ "email": res["metadatas"][0].get("email"),
237
+ "hashed_password": res["metadatas"][0].get("hashed_password"),
238
+ "name": res["metadatas"][0].get("name"),
239
+ }
240
+
241
+
242
+ def user_get_by_id(user_id: str) -> dict | None:
243
+ col = get_users_collection()
244
+ try:
245
+ res = col.get(ids=[user_id])
246
+ if not res["ids"]:
247
+ return None
248
+ return {
249
+ "user_id": res["ids"][0],
250
+ "email": res["metadatas"][0].get("email"),
251
+ "name": res["metadatas"][0].get("name"),
252
+ }
253
+ except Exception:
254
+ return None
255
+
256
+
257
+ # ---------- Sessions ----------
258
+ def get_sessions_collection():
259
+ return _get_or_create_collection("sessions")
260
+
261
+
262
+ def session_create(user_id: str) -> str:
263
+ session_id = str(uuid.uuid4())
264
+ col = get_sessions_collection()
265
+ col.add(
266
+ ids=[session_id],
267
+ documents=[""],
268
+ metadatas=[{"user_id": user_id}],
269
+ embeddings=[_dummy_embedding()],
270
+ )
271
+ return session_id
272
+
273
+
274
+ def session_get_user_id(session_id: str) -> str | None:
275
+ if not session_id:
276
+ return None
277
+ col = get_sessions_collection()
278
+ try:
279
+ res = col.get(ids=[session_id])
280
+ if not res["ids"]:
281
+ return None
282
+ return res["metadatas"][0].get("user_id")
283
+ except Exception:
284
+ return None
285
+
286
+
287
+ # ---------- User documents (extracted text from PDFs) ----------
288
+ def get_user_documents_collection():
289
+ return _get_or_create_collection("user_documents")
290
+
291
+
292
+ def _doc_id(user_id: str, path: str) -> str:
293
+ # ChromaDB ids: no pipe in path to avoid collision
294
+ safe_path = path.replace("|", "\x00")
295
+ return f"{user_id}|{safe_path}"
296
+
297
+
298
+ def _truncate_utf8_bytes(text: str, max_bytes: int) -> tuple[str, int]:
299
+ raw = (text or "").encode("utf-8")
300
+ if len(raw) <= max_bytes:
301
+ return (text or ""), len(raw)
302
+ cut = raw[: max(0, max_bytes)]
303
+ while cut:
304
+ try:
305
+ return cut.decode("utf-8"), len(raw)
306
+ except UnicodeDecodeError:
307
+ cut = cut[:-1]
308
+ return "", len(raw)
309
+
310
+
311
+ def user_document_upsert(user_id: str, path: str, content: str, original_filename: str):
312
+ """Store extracted text for a path with metadata (original PDFs/images stay on the client)."""
313
+ col = get_user_documents_collection()
314
+ doc_id = _doc_id(user_id, path)
315
+ trimmed, full_bytes = _truncate_utf8_bytes(content or "", USER_DOCUMENT_MAX_BYTES)
316
+ stored_bytes = len((trimmed or "").encode("utf-8"))
317
+ truncated = int(stored_bytes < full_bytes)
318
+ col.upsert(
319
+ ids=[doc_id],
320
+ documents=[trimmed],
321
+ metadatas=[
322
+ {
323
+ "user_id": str(user_id),
324
+ "path": str(path or ""),
325
+ "original_filename": str(original_filename or ""),
326
+ "truncated": truncated,
327
+ "content_bytes": int(full_bytes),
328
+ "stored_bytes": int(stored_bytes),
329
+ }
330
+ ],
331
+ embeddings=[_dummy_embedding()],
332
+ )
333
+
334
+
335
+ def user_document_delete_many(user_id: str, path_filter=None):
336
+ """Delete documents for user_id. path_filter: if callable(path) -> bool, only delete matching paths."""
337
+ col = get_user_documents_collection()
338
+ res = col.get(where={"user_id": user_id})
339
+ if not res["ids"]:
340
+ return
341
+ ids_to_delete = []
342
+ for i, doc_id in enumerate(res["ids"]):
343
+ path = res["metadatas"][i].get("path", "")
344
+ if path_filter is None or path_filter(path):
345
+ ids_to_delete.append(doc_id)
346
+ if ids_to_delete:
347
+ col.delete(ids=ids_to_delete)
348
+
349
+
350
+ def user_document_delete_by_path(user_id: str, path: str):
351
+ doc_id = _doc_id(user_id, path)
352
+ col = get_user_documents_collection()
353
+ try:
354
+ col.delete(ids=[doc_id])
355
+ except Exception:
356
+ pass
357
+
358
+
359
+ def user_document_get_content(user_id: str, path: str) -> str | None:
360
+ col = get_user_documents_collection()
361
+ doc_id = _doc_id(user_id, path)
362
+ try:
363
+ res = col.get(ids=[doc_id], include=["documents"])
364
+ if not res.get("ids"):
365
+ return None
366
+ docs = res.get("documents") or []
367
+ return docs[0] if docs else None
368
+ except Exception:
369
+ return None
370
+
371
+
372
+ def user_documents_relocate_prefix(user_id: str, old_prefix: str, new_prefix: str) -> int:
373
+ """Rename stored document paths under old_prefix to new_prefix (longest paths first)."""
374
+ col = get_user_documents_collection()
375
+ res = col.get(where={"user_id": user_id}, include=["metadatas"])
376
+ metas = res.get("metadatas") or []
377
+ pairs: list[tuple[str, str]] = []
378
+ for m in metas:
379
+ p = ((m or {}).get("path") or "").replace("\\", "/")
380
+ if p == old_prefix:
381
+ pairs.append((p, new_prefix))
382
+ elif p.startswith(old_prefix + "/"):
383
+ pairs.append((p, new_prefix + p[len(old_prefix) :]))
384
+ pairs.sort(key=lambda x: -len(x[0]))
385
+ n = 0
386
+ for op, np in pairs:
387
+ if op != np and user_document_rename_path(user_id, op, np):
388
+ n += 1
389
+ return n
390
+
391
+
392
+ def user_document_rename_path(user_id: str, old_path: str, new_path: str) -> bool:
393
+ """Move stored extracted text from old_path to new_path."""
394
+ col = get_user_documents_collection()
395
+ oid = _doc_id(user_id, old_path)
396
+ try:
397
+ res = col.get(ids=[oid], include=["documents", "metadatas"])
398
+ if not res.get("ids"):
399
+ return False
400
+ content = (res.get("documents") or [""])[0] or ""
401
+ meta = res.get("metadatas")[0] or {}
402
+ ofn = meta.get("original_filename") or os.path.basename(new_path.replace("\\", "/"))
403
+ col.delete(ids=[oid])
404
+ user_document_upsert(user_id, new_path, content, ofn)
405
+ return True
406
+ except Exception:
407
+ return False
408
+
409
+
410
+ # ---------- OneNote OAuth tokens/state ----------
411
+ def get_onenote_tokens_collection():
412
+ return _get_or_create_collection("onenote_tokens")
413
+
414
+
415
+ def get_onenote_oauth_state_collection():
416
+ return _get_or_create_collection("onenote_oauth_states")
417
+
418
+
419
+ def _oauth_state_id(state: str) -> str:
420
+ return f"state|{state}"
421
+
422
+
423
+ def onenote_oauth_state_create(user_id: str, state: str, expires_at_epoch: int) -> None:
424
+ col = get_onenote_oauth_state_collection()
425
+ col.upsert(
426
+ ids=[_oauth_state_id(state)],
427
+ documents=[""],
428
+ metadatas=[{"user_id": str(user_id), "expires_at": int(expires_at_epoch)}],
429
+ embeddings=[_dummy_embedding()],
430
+ )
431
+
432
+
433
+ def onenote_oauth_state_pop_user_id(state: str) -> str | None:
434
+ col = get_onenote_oauth_state_collection()
435
+ sid = _oauth_state_id(state)
436
+ try:
437
+ res = col.get(ids=[sid], include=["metadatas"])
438
+ if not res.get("ids"):
439
+ return None
440
+ meta = (res.get("metadatas") or [{}])[0] or {}
441
+ try:
442
+ exp = int(meta.get("expires_at") or 0)
443
+ except Exception:
444
+ exp = 0
445
+ user_id = str(meta.get("user_id") or "")
446
+ col.delete(ids=[sid])
447
+ if not user_id:
448
+ return None
449
+ if exp and exp < int(time.time()):
450
+ return None
451
+ return user_id
452
+ except Exception:
453
+ return None
454
+
455
+
456
+ def onenote_token_upsert(user_id: str, token_payload: dict) -> None:
457
+ col = get_onenote_tokens_collection()
458
+ uid = str(user_id)
459
+ try:
460
+ raw = json.dumps(token_payload or {}, ensure_ascii=False)
461
+ except Exception:
462
+ raw = "{}"
463
+ expires_at = 0
464
+ try:
465
+ expires_at = int((token_payload or {}).get("expires_at") or 0)
466
+ except Exception:
467
+ expires_at = 0
468
+ col.upsert(
469
+ ids=[uid],
470
+ documents=[raw],
471
+ metadatas=[{"user_id": uid, "expires_at": expires_at}],
472
+ embeddings=[_dummy_embedding()],
473
+ )
474
+
475
+
476
+ def onenote_token_get(user_id: str) -> dict | None:
477
+ col = get_onenote_tokens_collection()
478
+ uid = str(user_id)
479
+ try:
480
+ res = col.get(ids=[uid], include=["documents"])
481
+ if not res.get("ids"):
482
+ return None
483
+ raw = (res.get("documents") or ["{}"])[0] or "{}"
484
+ data = json.loads(raw)
485
+ return data if isinstance(data, dict) else None
486
+ except Exception:
487
+ return None
backend/extract_api.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extract text from PDFs and images (bytes or legacy folder paths)."""
2
+ import os
3
+ from PIL import Image
4
+ import pytesseract
5
+ import fitz # PyMuPDF
6
+
7
+
8
+ def extract_text_from_pdf_bytes(pdf_bytes: bytes) -> str:
9
+ """Extract text from PDF bytes in memory. Does not write to disk."""
10
+ doc = fitz.open(stream=pdf_bytes, filetype="pdf")
11
+ try:
12
+ text = ""
13
+ for page in doc:
14
+ text += page.get_text()
15
+ return text
16
+ finally:
17
+ doc.close()
18
+
19
+
20
+ def extract_text(notes_root: str, subject: str):
21
+ """
22
+ Extract text from PDFs and images in notes_root/subject.
23
+ Saves .txt files next to originals. Returns extracted content for saving to MongoDB.
24
+ """
25
+ folder_path = os.path.join(notes_root, subject)
26
+ if not os.path.exists(folder_path):
27
+ return {"error": "Folder does not exist.", "processed_files": [], "extracted_texts": {}}
28
+
29
+ extracted = {}
30
+ processed_files = []
31
+
32
+ for fname in os.listdir(folder_path):
33
+ fpath = os.path.join(folder_path, fname)
34
+ if os.path.isfile(fpath):
35
+ try:
36
+ if fname.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tiff')):
37
+ print(f"🔄 Extracting text from image: {fname}")
38
+ text = pytesseract.image_to_string(Image.open(fpath))
39
+ extracted[fname] = text
40
+ elif fname.lower().endswith('.pdf'):
41
+ print(f"🔄 Extracting text from PDF: {fname}")
42
+ pdf = fitz.open(fpath)
43
+ pdf_text = ""
44
+ for page in pdf:
45
+ pdf_text += page.get_text()
46
+ pdf.close()
47
+ extracted[fname] = pdf_text
48
+ else:
49
+ print(f"⚠️ Skipping unsupported file: {fname}")
50
+ continue
51
+
52
+ # Save extracted text to .txt file (local only; DB is updated by caller)
53
+ txt_filename = os.path.splitext(fname)[0] + ".txt"
54
+ txt_path = os.path.join(folder_path, txt_filename)
55
+ with open(txt_path, "w", encoding="utf-8") as f:
56
+ f.write(extracted[fname])
57
+
58
+ processed_files.append({
59
+ "original_file": fname,
60
+ "text_file": txt_filename,
61
+ "text_length": len(extracted[fname]),
62
+ })
63
+ print(f"✅ Saved text to {txt_filename}")
64
+
65
+ except Exception as e:
66
+ print(f"❌ Error processing {fname}: {str(e)}")
67
+ continue
68
+
69
+ return {
70
+ "message": f"Extracted text from {len(processed_files)} files",
71
+ "processed_files": processed_files,
72
+ "extracted_texts": extracted,
73
+ }
74
+
75
+
76
+ def extract_text_from_image_bytes(data: bytes) -> str:
77
+ import io
78
+ img = Image.open(io.BytesIO(data))
79
+ return pytesseract.image_to_string(img)
80
+
backend/file_meta.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-user file metadata (primary authority, related paths) stored in ChromaDB (vfs collection)."""
2
+ from typing import Any
3
+
4
+ from backend.chroma_store import vfs_get_file_meta_dict, vfs_set_file_meta_dict
5
+
6
+
7
+ def load_file_meta(user_id: str) -> dict[str, dict[str, Any]]:
8
+ return vfs_get_file_meta_dict(user_id)
9
+
10
+
11
+ def save_file_meta(user_id: str, data: dict[str, dict[str, Any]]) -> None:
12
+ vfs_set_file_meta_dict(user_id, data)
13
+
14
+
15
+ def get_entry(user_id: str, rel_path: str) -> dict[str, Any]:
16
+ rel_path = rel_path.replace("\\", "/").strip("/")
17
+ meta = load_file_meta(user_id)
18
+ return dict(meta.get(rel_path) or {})
19
+
20
+
21
+ def set_entry(user_id: str, rel_path: str, **fields) -> dict[str, Any]:
22
+ rel_path = rel_path.replace("\\", "/").strip("/")
23
+ meta = load_file_meta(user_id)
24
+ cur = dict(meta.get(rel_path) or {})
25
+ for k, v in fields.items():
26
+ if v is None:
27
+ cur.pop(k, None)
28
+ else:
29
+ cur[k] = v
30
+ meta[rel_path] = cur
31
+ save_file_meta(user_id, meta)
32
+ return cur
33
+
34
+
35
+ def delete_keys_for_prefix(user_id: str, folder_prefix: str) -> None:
36
+ folder_prefix = folder_prefix.replace("\\", "/").strip("/")
37
+ meta = load_file_meta(user_id)
38
+ keys = [k for k in meta if k == folder_prefix or k.startswith(folder_prefix + "/")]
39
+ for k in keys:
40
+ del meta[k]
41
+ save_file_meta(user_id, meta)
42
+
43
+
44
+ def delete_key(user_id: str, rel_path: str) -> None:
45
+ rel_path = rel_path.replace("\\", "/").strip("/")
46
+ meta = load_file_meta(user_id)
47
+ if rel_path in meta:
48
+ del meta[rel_path]
49
+ save_file_meta(user_id, meta)
50
+
51
+
52
+ def chunk_paths_for_file(rel_path: str) -> list[str]:
53
+ """Chroma `path` values to update when user toggles metadata on this file."""
54
+ import os
55
+
56
+ rel_path = rel_path.replace("\\", "/").strip("/")
57
+ lower = rel_path.lower()
58
+ out = [rel_path]
59
+ if lower.endswith((".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".gif", ".webp")):
60
+ base = os.path.splitext(rel_path)[0] + ".txt"
61
+ if base != rel_path:
62
+ out.append(base)
63
+ return list(dict.fromkeys(out))
64
+
65
+
66
+ def merged_meta_for_chunk(
67
+ user_id: str,
68
+ chunk_path: str,
69
+ source_file: str,
70
+ ) -> dict[str, Any]:
71
+ """Resolve file_meta for a chunk: try chunk path, .pdf/.txt sibling, and image→txt."""
72
+ import os
73
+
74
+ chunk_path = chunk_path.replace("\\", "/")
75
+ meta = load_file_meta(user_id)
76
+ candidates = [chunk_path]
77
+ base, ext = os.path.splitext(chunk_path)
78
+ ext_l = ext.lower()
79
+ if ext_l == ".txt":
80
+ for img_ext in (".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tiff"):
81
+ candidates.append(base + img_ext)
82
+ if base:
83
+ candidates.append(base + ".pdf")
84
+ elif ext_l == ".pdf":
85
+ candidates.append(base + ".txt")
86
+ for c in candidates:
87
+ c = c.strip("/")
88
+ if c in meta:
89
+ return dict(meta[c])
90
+ return {}
91
+
92
+
93
+ def file_meta_rename_path(user_id: str, old_p: str, new_p: str) -> None:
94
+ old_p = old_p.replace("\\", "/").strip("/")
95
+ new_p = new_p.replace("\\", "/").strip("/")
96
+ meta = load_file_meta(user_id)
97
+ if old_p not in meta:
98
+ return
99
+ meta[new_p] = meta.pop(old_p)
100
+ save_file_meta(user_id, meta)
101
+
102
+
103
+ def file_meta_relocate_prefix(user_id: str, old_prefix: str, new_prefix: str) -> None:
104
+ old_prefix = old_prefix.replace("\\", "/").strip("/")
105
+ new_prefix = new_prefix.replace("\\", "/").strip("/")
106
+ meta = load_file_meta(user_id)
107
+ keys = sorted(
108
+ [k for k in meta if k == old_prefix or k.startswith(old_prefix + "/")],
109
+ key=lambda x: -len(x),
110
+ )
111
+ for k in keys:
112
+ if k == old_prefix:
113
+ nk = new_prefix
114
+ else:
115
+ nk = new_prefix + "/" + k[len(old_prefix) + 1 :]
116
+ meta[nk] = meta.pop(k)
117
+ save_file_meta(user_id, meta)
118
+
119
+
120
+ def course_id_from_path(rel_path: str) -> str:
121
+ rel_path = rel_path.replace("\\", "/").strip("/")
122
+ if not rel_path:
123
+ return "root"
124
+ return rel_path.split("/")[0]
backend/ingest_api.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ingest text into ChromaDB using the centralized client and per-user collection (user_{user_id}_notes)."""
2
+ import os
3
+ from sentence_transformers import SentenceTransformer
4
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
5
+
6
+ from backend.chroma_store import get_user_collection
7
+ from backend.file_meta import course_id_from_path, merged_meta_for_chunk
8
+
9
+ CHUNK_SIZE = 750
10
+ CHUNK_OVERLAP = 100
11
+ BATCH_SIZE = 50
12
+
13
+
14
+ def _chunk_text(text: str):
15
+ splitter = RecursiveCharacterTextSplitter(chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)
16
+ return splitter.split_text(text)
17
+
18
+
19
+ def _base_metadata_user(user_id: str, path: str, source_file: str) -> dict:
20
+ fm = merged_meta_for_chunk(user_id, path, source_file)
21
+ # Chroma metadata: str, int, float, bool — use int flags for broad server/Cloud compatibility.
22
+ return {
23
+ "user_id": str(user_id),
24
+ "path": str(path or ""),
25
+ "source_file": str(source_file or ""),
26
+ "course_id": str(course_id_from_path(path)),
27
+ "is_primary_authority": int(bool(fm.get("is_primary_authority"))),
28
+ "doc_type": str(fm.get("doc_type") or "other"),
29
+ }
30
+
31
+
32
+ def _add_chunks_to_collection(collection, chunks: list, path: str, source_file: str, model, user_id: str):
33
+ """Add chunk text, embeddings, and metadata to the user's Chroma collection."""
34
+ try:
35
+ existing = collection.get(where={"path": path}, include=[])
36
+ if existing["ids"]:
37
+ collection.delete(ids=existing["ids"])
38
+ except Exception:
39
+ pass
40
+ path_safe = path.replace("|", "\x00")
41
+ for i in range(0, len(chunks), BATCH_SIZE):
42
+ batch = chunks[i : i + BATCH_SIZE]
43
+ embeddings = model.encode(batch).tolist()
44
+ ids = [f"{path_safe}|{i + j}" for j in range(len(batch))]
45
+ metadatas = []
46
+ for j, _chunk in enumerate(batch):
47
+ m = _base_metadata_user(user_id, path, source_file)
48
+ m["chunk_index"] = i + j
49
+ metadatas.append(m)
50
+ collection.add(documents=batch, embeddings=embeddings, ids=ids, metadatas=metadatas)
51
+
52
+
53
+ def refresh_metadata_for_paths(user_id: str, chroma_paths: list[str]) -> int:
54
+ """Update metadata on existing chunks (e.g. after toggling primary authority)."""
55
+ if not chroma_paths:
56
+ return 0
57
+ col = get_user_collection(user_id)
58
+ updated = 0
59
+ for path in chroma_paths:
60
+ try:
61
+ res = col.get(where={"path": path}, include=["metadatas"])
62
+ ids = res.get("ids") or []
63
+ if not ids:
64
+ continue
65
+ metas = []
66
+ for old in res.get("metadatas") or []:
67
+ old = old or {}
68
+ p = old.get("path") or path
69
+ sf = old.get("source_file") or ""
70
+ nm = _base_metadata_user(user_id, p, sf)
71
+ if "chunk_index" in old:
72
+ nm["chunk_index"] = old["chunk_index"]
73
+ metas.append(nm)
74
+ col.update(ids=ids, metadatas=metas)
75
+ updated += len(ids)
76
+ except Exception:
77
+ continue
78
+ return updated
79
+
80
+
81
+ def ingest_pdf_in_memory(user_id: str, pdf_bytes: bytes, filename: str, rel_path: str, notes_root: str | None = None):
82
+ """
83
+ Read PDF from bytes, extract text in memory, chunk (~750 chars, ~100 overlap), and add to
84
+ the user's ChromaDB collection. Does not write any file to disk.
85
+ """
86
+ from backend.extract_api import extract_text_from_pdf_bytes
87
+
88
+ _ = notes_root # unused; kept for call-site compatibility
89
+ text = extract_text_from_pdf_bytes(pdf_bytes)
90
+ if not text or not text.strip():
91
+ return {"chunks_created": 0, "message": "No text extracted from PDF."}
92
+ collection = get_user_collection(user_id)
93
+ model = SentenceTransformer("all-MiniLM-L6-v2")
94
+ chunks = _chunk_text(text)
95
+ _add_chunks_to_collection(collection, chunks, rel_path, filename, model, user_id)
96
+ return {"chunks_created": len(chunks), "message": f"Ingested {len(chunks)} chunks from PDF."}
97
+
98
+
99
+ def ingest_folder(notes_root: str, user_id: str, subject: str):
100
+ """Ingest all text files from notes_root/subject into the user's ChromaDB collection."""
101
+ folder_path = os.path.join(notes_root, subject)
102
+ if not os.path.exists(folder_path):
103
+ return {"error": "Folder does not exist.", "chunks_created": 0}
104
+
105
+ items = []
106
+ for fname in os.listdir(folder_path):
107
+ if not fname.endswith(".txt"):
108
+ continue
109
+ txt_path = os.path.join(folder_path, fname)
110
+ try:
111
+ with open(txt_path, "r", encoding="utf-8") as f:
112
+ text = f.read()
113
+ if text.strip():
114
+ rel_path = os.path.join(subject, fname).replace("\\", "/")
115
+ items.append((rel_path, fname, text))
116
+ except OSError as e:
117
+ print(f"❌ Error reading {fname}: {str(e)}")
118
+ continue
119
+
120
+ if not items:
121
+ return {"error": "No extracted text found in folder.", "chunks_created": 0}
122
+
123
+ collection = get_user_collection(user_id)
124
+ model = SentenceTransformer("all-MiniLM-L6-v2")
125
+ total_chunks = 0
126
+ for rel_path, source_file, text in items:
127
+ chunks = _chunk_text(text)
128
+ _add_chunks_to_collection(collection, chunks, rel_path, source_file, model, user_id)
129
+ total_chunks += len(chunks)
130
+ return {
131
+ "message": f"Ingested {total_chunks} chunks for subject '{subject}' into ChromaDB.",
132
+ "chunks_created": total_chunks,
133
+ "files_processed": [x[1] for x in items],
134
+ "final_count": collection.count(),
135
+ }
136
+
137
+
138
+ def ingest_text_for_path(user_id: str, rel_path: str, source_file: str, text: str):
139
+ """Ingest or replace chunks for a single extracted text path (e.g. after vision OCR)."""
140
+ if not text or not text.strip():
141
+ return {"chunks_created": 0, "message": "Empty text."}
142
+ collection = get_user_collection(user_id)
143
+ model = SentenceTransformer("all-MiniLM-L6-v2")
144
+ chunks = _chunk_text(text)
145
+ _add_chunks_to_collection(collection, chunks, rel_path, source_file, model, user_id)
146
+ return {"chunks_created": len(chunks), "message": f"Ingested {len(chunks)} chunks."}
147
+
148
+
149
+ def chunks_relocate_path(user_id: str, old_path: str, new_path: str, source_file: str | None = None) -> int:
150
+ """Move all chunks from old_path to new_path (same text and embeddings, updated metadata)."""
151
+ col = get_user_collection(user_id)
152
+ res = col.get(where={"path": old_path}, include=["documents", "embeddings", "metadatas"])
153
+ docs = res.get("documents") or []
154
+ ids = res.get("ids") or []
155
+ if not ids:
156
+ return 0
157
+ embs = res.get("embeddings")
158
+ model = SentenceTransformer("all-MiniLM-L6-v2")
159
+ if embs is None or len(embs) != len(docs):
160
+ embs = model.encode(docs).tolist()
161
+ else:
162
+ embs = list(embs)
163
+ col.delete(ids=ids)
164
+ sf = source_file or os.path.basename(new_path.replace("\\", "/"))
165
+ old_metas = res.get("metadatas") or []
166
+ metadatas = []
167
+ for k in range(len(docs)):
168
+ m = _base_metadata_user(user_id, new_path, sf)
169
+ om = old_metas[k] if k < len(old_metas) else {}
170
+ if isinstance(om, dict) and "chunk_index" in om:
171
+ try:
172
+ m["chunk_index"] = int(om["chunk_index"])
173
+ except (TypeError, ValueError):
174
+ m["chunk_index"] = k
175
+ else:
176
+ m["chunk_index"] = k
177
+ metadatas.append(m)
178
+ path_safe = new_path.replace("|", "\x00")
179
+ new_ids = [f"{path_safe}|{j}" for j in range(len(docs))]
180
+ col.add(ids=new_ids, documents=list(docs), embeddings=list(embs), metadatas=metadatas)
181
+ return len(docs)
182
+
183
+
184
+ def chunks_relocate_folder_prefix(user_id: str, old_prefix: str, new_prefix: str) -> int:
185
+ """Rewrite chunk paths for every document under old_prefix to new_prefix."""
186
+ old_prefix = old_prefix.replace("\\", "/").strip("/")
187
+ new_prefix = new_prefix.replace("\\", "/").strip("/")
188
+ col = get_user_collection(user_id)
189
+ res = col.get(include=["metadatas"])
190
+ metas = res.get("metadatas") or []
191
+ paths = {((m or {}).get("path") or "").replace("\\", "/") for m in metas if (m or {}).get("path")}
192
+ todo: list[tuple[str, str]] = []
193
+ for p in paths:
194
+ if p == old_prefix:
195
+ todo.append((p, new_prefix))
196
+ elif p.startswith(old_prefix + "/"):
197
+ todo.append((p, new_prefix + p[len(old_prefix) :]))
198
+ todo.sort(key=lambda x: -len(x[0]))
199
+ moved = 0
200
+ for old_p, new_p in todo:
201
+ if old_p == new_p:
202
+ continue
203
+ sf = None
204
+ for m in metas:
205
+ if ((m or {}).get("path") or "").replace("\\", "/") == old_p:
206
+ sf = (m or {}).get("source_file")
207
+ break
208
+ moved += chunks_relocate_path(user_id, old_p, new_p, sf)
209
+ return moved
backend/llm_pipeline.py ADDED
@@ -0,0 +1,756 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LLM + OCR: Sarvam AI — Document Intelligence (Sarvam Vision) + Chat Completions."""
2
+ import json
3
+ import os
4
+ import re
5
+ import tempfile
6
+ import unicodedata
7
+ import zipfile
8
+ from typing import Any
9
+
10
+ import httpx
11
+
12
+ # Chat models (see https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/chat-completion/overview)
13
+ _DEFAULT_MODEL_RAG = "sarvam-105b"
14
+ _DEFAULT_MODEL_STUDY = "sarvam-30b"
15
+
16
+ _GROUNDING_STOPWORDS = {
17
+ "about", "after", "again", "also", "among", "another", "because", "before", "being", "between",
18
+ "both", "could", "does", "each", "from", "have", "into", "more", "most", "other", "over", "same",
19
+ "some", "such", "than", "that", "their", "there", "these", "they", "this", "those", "through",
20
+ "under", "using", "very", "what", "when", "where", "which", "while", "with", "would",
21
+ }
22
+
23
+
24
+ def _sarvam_api_key() -> str | None:
25
+ k = os.getenv("SARVAM_API_KEY")
26
+ return k.strip() if k else None
27
+
28
+
29
+ def _chat_base_url() -> str:
30
+ return os.getenv("SARVAM_API_BASE", "https://api.sarvam.ai").rstrip("/")
31
+
32
+
33
+ def _model_rag() -> str:
34
+ return os.getenv("SARVAM_MODEL_RAG", _DEFAULT_MODEL_RAG).strip()
35
+
36
+
37
+ def _model_study() -> str:
38
+ return os.getenv("SARVAM_MODEL_STUDY", _DEFAULT_MODEL_STUDY).strip()
39
+
40
+
41
+ def _sarvam_chat_complete(
42
+ messages: list[dict[str, str]],
43
+ *,
44
+ model: str,
45
+ max_tokens: int,
46
+ temperature: float,
47
+ ) -> tuple[str | None, str | None]:
48
+ key = _sarvam_api_key()
49
+ if not key:
50
+ return None, "SARVAM_API_KEY not configured"
51
+ url = f"{_chat_base_url()}/v1/chat/completions"
52
+ try:
53
+ r = httpx.post(
54
+ url,
55
+ headers={
56
+ "Authorization": f"Bearer {key}",
57
+ "Content-Type": "application/json",
58
+ },
59
+ json={
60
+ "model": model,
61
+ "messages": messages,
62
+ "max_tokens": max_tokens,
63
+ "temperature": temperature,
64
+ },
65
+ timeout=300.0,
66
+ )
67
+ data = r.json()
68
+ if r.status_code >= 400:
69
+ err = data.get("error") if isinstance(data.get("error"), dict) else {}
70
+ msg = err.get("message") if isinstance(err, dict) else None
71
+ return None, msg or r.text or f"HTTP {r.status_code}"
72
+ choices = data.get("choices") or []
73
+ if not choices:
74
+ return None, "no choices in response"
75
+ content = (choices[0].get("message") or {}).get("content")
76
+ if content is None or not str(content).strip():
77
+ return None, "empty model content"
78
+ return str(content).strip(), None
79
+ except httpx.RequestError as e:
80
+ return None, str(e)
81
+ except Exception as e:
82
+ return None, str(e)
83
+
84
+
85
+ def _prepare_image_for_document_intel(image_bytes: bytes, mime: str) -> tuple[bytes, str]:
86
+ """Document Intelligence accepts PNG/JPEG/PDF; normalize webp/gif to JPEG."""
87
+ m = (mime or "image/jpeg").lower()
88
+ if m in ("image/webp", "image/gif"):
89
+ from io import BytesIO
90
+
91
+ from PIL import Image
92
+
93
+ im = Image.open(BytesIO(image_bytes)).convert("RGB")
94
+ out = BytesIO()
95
+ im.save(out, format="JPEG", quality=92)
96
+ return out.getvalue(), ".jpg"
97
+ if m == "image/png":
98
+ return image_bytes, ".png"
99
+ return image_bytes, ".jpg"
100
+
101
+
102
+ def _prepare_document_for_document_intel(file_bytes: bytes, mime: str) -> tuple[bytes, str]:
103
+ """Normalize uploads for Sarvam Document Intelligence (image or PDF)."""
104
+ m = (mime or "").lower().strip()
105
+ if m == "application/pdf":
106
+ return file_bytes, ".pdf"
107
+ return _prepare_image_for_document_intel(file_bytes, m or "image/jpeg")
108
+
109
+
110
+ def _extract_markdown_from_output_zip(zip_path: str) -> str:
111
+ with zipfile.ZipFile(zip_path, "r") as z:
112
+ names = sorted(z.namelist())
113
+ md_names = [n for n in names if n.lower().endswith(".md")]
114
+ html_names = [n for n in names if n.lower().endswith((".html", ".htm"))]
115
+ pick = (md_names[0] if md_names else None) or (html_names[0] if html_names else None) or (
116
+ names[0] if names else None
117
+ )
118
+ if not pick:
119
+ return ""
120
+ return z.read(pick).decode("utf-8", errors="replace").strip()
121
+
122
+
123
+ def _document_intelligence_image(image_bytes: bytes, mime: str) -> tuple[str | None, str | None]:
124
+ """
125
+ OCR / layout text via Sarvam Document Intelligence (Sarvam Vision).
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_image_for_document_intel(image_bytes, mime)
137
+ tmp_image: str | None = None
138
+ tmp_zip: str | None = None
139
+ timeout = float(os.getenv("SARVAM_DOC_INTEL_TIMEOUT", "180"))
140
+ try:
141
+ fd, tmp_image = tempfile.mkstemp(suffix=suffix)
142
+ os.write(fd, raw_bytes)
143
+ os.close(fd)
144
+ fd = -1
145
+
146
+ client = SarvamAI(api_subscription_key=key, timeout=timeout)
147
+ lang = os.getenv("SARVAM_DOC_INTEL_LANGUAGE", "en-IN").strip()
148
+ job = client.document_intelligence.create_job(language=lang, output_format="md")
149
+ job.upload_file(tmp_image)
150
+ job.start()
151
+ status = job.wait_until_complete(timeout=timeout)
152
+ state = str(getattr(status, "job_state", "") or "")
153
+ if state not in ("Completed", "PartiallyCompleted"):
154
+ return None, f"Document intelligence job state: {state or 'unknown'}"
155
+
156
+ zfd, tmp_zip = tempfile.mkstemp(suffix=".zip")
157
+ os.close(zfd)
158
+ job.download_output(tmp_zip)
159
+ text = _extract_markdown_from_output_zip(tmp_zip)
160
+ if not text:
161
+ return None, "empty document intelligence output"
162
+ return text, None
163
+ except TimeoutError as e:
164
+ return None, str(e)
165
+ except Exception as e:
166
+ return None, str(e)
167
+ finally:
168
+ if tmp_image and os.path.isfile(tmp_image):
169
+ try:
170
+ os.unlink(tmp_image)
171
+ except OSError:
172
+ pass
173
+ if tmp_zip and os.path.isfile(tmp_zip):
174
+ try:
175
+ os.unlink(tmp_zip)
176
+ except OSError:
177
+ pass
178
+
179
+
180
+ def transcribe_handwritten_image(image_bytes: bytes, mime: str = "image/jpeg") -> tuple[str | None, str | None]:
181
+ """Sarvam Vision (Document Intelligence) → markdown/plain text from note images."""
182
+ return _document_intelligence_image(image_bytes, mime)
183
+
184
+
185
+ def transcribe_document_bytes(file_bytes: bytes, mime: str = "application/pdf") -> tuple[str | None, str | None]:
186
+ """Sarvam Vision (Document Intelligence) OCR for uploaded PDFs/images."""
187
+ key = _sarvam_api_key()
188
+ if not key:
189
+ return None, "SARVAM_API_KEY not configured"
190
+ try:
191
+ from sarvamai import SarvamAI
192
+ except ImportError:
193
+ return None, "sarvamai package not installed (pip install sarvamai)"
194
+ raw_bytes, suffix = _prepare_document_for_document_intel(file_bytes, mime)
195
+ tmp_file: str | None = None
196
+ tmp_zip: str | None = None
197
+ timeout = float(os.getenv("SARVAM_DOC_INTEL_TIMEOUT", "180"))
198
+ try:
199
+ fd, tmp_file = tempfile.mkstemp(suffix=suffix)
200
+ os.write(fd, raw_bytes)
201
+ os.close(fd)
202
+ client = SarvamAI(api_subscription_key=key, timeout=timeout)
203
+ lang = os.getenv("SARVAM_DOC_INTEL_LANGUAGE", "en-IN").strip()
204
+ job = client.document_intelligence.create_job(language=lang, output_format="md")
205
+ job.upload_file(tmp_file)
206
+ job.start()
207
+ status = job.wait_until_complete(timeout=timeout)
208
+ state = str(getattr(status, "job_state", "") or "")
209
+ if state not in ("Completed", "PartiallyCompleted"):
210
+ return None, f"Document intelligence job state: {state or 'unknown'}"
211
+ zfd, tmp_zip = tempfile.mkstemp(suffix=".zip")
212
+ os.close(zfd)
213
+ job.download_output(tmp_zip)
214
+ text = _extract_markdown_from_output_zip(tmp_zip)
215
+ if not text:
216
+ return None, "empty document intelligence output"
217
+ return text, None
218
+ except TimeoutError as e:
219
+ return None, str(e)
220
+ except Exception as e:
221
+ return None, str(e)
222
+ finally:
223
+ if tmp_file and os.path.isfile(tmp_file):
224
+ try:
225
+ os.unlink(tmp_file)
226
+ except OSError:
227
+ pass
228
+ if tmp_zip and os.path.isfile(tmp_zip):
229
+ try:
230
+ os.unlink(tmp_zip)
231
+ except OSError:
232
+ pass
233
+
234
+
235
+ def sarvam_general_answer(question: str) -> tuple[str | None, str | None]:
236
+ """Answer without retrieving text from Chroma (no RAG / no stored course excerpts)."""
237
+ messages: list[dict[str, str]] = [
238
+ {
239
+ "role": "system",
240
+ "content": (
241
+ "You are a clear, accurate teaching assistant. Answer the student's question directly. "
242
+ "If essential information is missing, say what you would need to know."
243
+ ),
244
+ },
245
+ {"role": "user", "content": question},
246
+ ]
247
+ return _sarvam_chat_complete(
248
+ messages,
249
+ model=_model_rag(),
250
+ max_tokens=8192,
251
+ temperature=0.3,
252
+ )
253
+
254
+
255
+ def sarvam_rag_answer(question: str, context: str) -> tuple[str | None, str | None]:
256
+ """Answer strictly from provided notes context."""
257
+ ctx = (context or "").strip()[:60000]
258
+ q = (question or "").strip()
259
+ if not q:
260
+ return None, "Empty query"
261
+ messages: list[dict[str, str]] = [
262
+ {
263
+ "role": "system",
264
+ "content": (
265
+ "You are a teaching assistant answering ONLY from the provided notes excerpts. "
266
+ "Do not claim inability to access files. "
267
+ "If answer is not present in the excerpts, say that clearly and suggest what to open/upload."
268
+ ),
269
+ },
270
+ {
271
+ "role": "user",
272
+ "content": (
273
+ f"Question:\n{q}\n\n"
274
+ f"Notes excerpts:\n{ctx}\n\n"
275
+ "Answer using only these excerpts."
276
+ ),
277
+ },
278
+ ]
279
+ return _sarvam_chat_complete(
280
+ messages,
281
+ model=_model_rag(),
282
+ max_tokens=4096,
283
+ temperature=0.2,
284
+ )
285
+
286
+
287
+ def _parse_json_loose(raw: str) -> Any:
288
+ raw = raw.strip()
289
+ raw = re.sub(r"^```(?:json)?\s*", "", raw)
290
+ raw = re.sub(r"\s*```\s*$", "", raw)
291
+ return json.loads(raw)
292
+
293
+
294
+ def _tokens(text: str) -> list[str]:
295
+ # 3+ chars: math/CS terms like "ref", "rref", "row"
296
+ return [
297
+ t
298
+ for t in re.findall(r"[a-zA-Z][a-zA-Z0-9]{2,}", (text or "").lower())
299
+ if t not in _GROUNDING_STOPWORDS
300
+ ]
301
+
302
+
303
+ def _primary_body_from_study_ctx(ctx: str) -> str:
304
+ marker = "--- PRIMARY FILE CONTENT ---"
305
+ i = (ctx or "").find(marker)
306
+ if i >= 0:
307
+ return (ctx[i + len(marker) :]).lstrip()
308
+ return ctx or ""
309
+
310
+
311
+ def _context_keywords(context: str) -> set[str]:
312
+ toks = _tokens(context)
313
+ if not toks:
314
+ return set()
315
+ freq: dict[str, int] = {}
316
+ for t in toks:
317
+ freq[t] = freq.get(t, 0) + 1
318
+ ranked = sorted(freq.items(), key=lambda kv: (-kv[1], -len(kv[0]), kv[0]))
319
+ return {k for k, _v in ranked[:250]}
320
+
321
+
322
+ def _grounded_enough(text: str, keywords: set[str], *, min_hits: int = 2) -> bool:
323
+ if not keywords:
324
+ return False
325
+ hits = len(set(_tokens(text)) & keywords)
326
+ return hits >= min_hits
327
+
328
+
329
+ def _normalize_study_match(s: str) -> str:
330
+ t = unicodedata.normalize("NFKC", s or "")
331
+ for u, a in (
332
+ ("\u2013", "-"),
333
+ ("\u2014", "-"),
334
+ ("\u2212", "-"),
335
+ ("\u00a0", " "),
336
+ ("\u200b", ""),
337
+ ):
338
+ t = t.replace(u, a)
339
+ return re.sub(r"\s+", " ", t.strip().lower())
340
+
341
+
342
+ def _contains_context_quote(context: str, quote: str) -> bool:
343
+ q = (quote or "").strip()
344
+ if len(q) < 12:
345
+ return False
346
+ ctx_raw = context or ""
347
+ # Fast path: exact / case-insensitive substring of raw notes (handles OCR spacing).
348
+ if q in ctx_raw:
349
+ return True
350
+ if q.lower() in ctx_raw.lower():
351
+ return True
352
+ ctx_n = _normalize_study_match(context)
353
+ qq = _normalize_study_match(q)
354
+ if len(qq) < 12:
355
+ return False
356
+ if qq in ctx_n:
357
+ return True
358
+ # Model may drop punctuation around matrices / LaTeX; alnum fold still ties to notes.
359
+ def fold(t: str) -> str:
360
+ return re.sub(r"[^a-z0-9]+", "", t)
361
+
362
+ qf, cf = fold(qq), fold(ctx_n)
363
+ return len(qf) >= 10 and qf in cf
364
+
365
+
366
+ def _pick_evidence_span(body: str, text_for_match: str, *, min_len: int = 12, max_len: int = 240) -> str:
367
+ """Choose a substring of body that best overlaps tokens from text_for_match (server-side evidence)."""
368
+ b = body or ""
369
+ if len(b) < min_len:
370
+ return ""
371
+ toks = [t for t in _tokens(text_for_match) if len(t) >= 3][:50]
372
+ win = min(max_len, len(b))
373
+ win = max(min_len, win)
374
+ step = max(40, win // 4)
375
+ best_i, best_score = 0, -1
376
+ upper = max(1, len(b) - win + 1)
377
+ for i in range(0, upper, step):
378
+ chunk = b[i : i + win]
379
+ cl = chunk.lower()
380
+ score = sum(1 for t in toks if t in cl) if toks else len(chunk)
381
+ if score > best_score:
382
+ best_score = score
383
+ best_i = i
384
+ span = b[best_i : best_i + win].strip()
385
+ if len(span) < min_len:
386
+ span = b[: min(max_len, len(b))].strip()
387
+ out = span[:max_len] if span else ""
388
+ if out and not _contains_context_quote(b, out):
389
+ out = b[: min(max_len, len(b))].strip()[:max_len]
390
+ return out
391
+
392
+
393
+ def _best_line_snippet(body: str, anchor_text: str, max_len: int = 220) -> str:
394
+ """Return a note line (or start of body) that best overlaps anchor tokens."""
395
+ b = body or ""
396
+ if len(b) < 12:
397
+ return ""
398
+ want = set(_tokens(anchor_text))
399
+ best_s, best_score = "", -1
400
+ for line in b.splitlines():
401
+ s = line.strip()
402
+ if len(s) < 12:
403
+ continue
404
+ got = set(_tokens(s))
405
+ score = len(want & got) if want else len(s)
406
+ if score > best_score:
407
+ best_score, best_s = score, s
408
+ if best_s and _contains_context_quote(b, best_s[:max_len]):
409
+ return best_s[:max_len].strip()
410
+ head = b[:max_len].strip()
411
+ return head if len(head) >= 12 else ""
412
+
413
+
414
+ def _token_overlap(a: str, b: str) -> int:
415
+ return len(set(_tokens(a)) & set(_tokens(b)))
416
+
417
+
418
+ def _finalize_evidence(primary_body: str, evidence: str, anchor_text: str, keywords: set[str]) -> str | None:
419
+ """Return evidence substring of primary_body: model quote, picked span, best line, or note head."""
420
+ body = (primary_body or "").strip()
421
+ if len(body) < 12:
422
+ return None
423
+ ev = (evidence or "").strip()
424
+ if ev and _contains_context_quote(body, ev):
425
+ return ev[:500]
426
+ picked = _pick_evidence_span(body, anchor_text)
427
+ if picked and _contains_context_quote(body, picked):
428
+ return picked[:500]
429
+ line_snip = _best_line_snippet(body, anchor_text)
430
+ if line_snip and _contains_context_quote(body, line_snip):
431
+ return line_snip[:500]
432
+ if _grounded_enough(anchor_text, keywords, min_hits=1):
433
+ head = body[: min(220, len(body))].strip()
434
+ if len(head) >= 12 and _contains_context_quote(body, head):
435
+ return head
436
+ return None
437
+
438
+
439
+ def _validate_flashcards(
440
+ items: Any, n: int, keywords: set[str], ctx: str, primary_body: str
441
+ ) -> list[dict[str, str]] | None:
442
+ if not isinstance(items, list):
443
+ return None
444
+ body = (primary_body or _primary_body_from_study_ctx(ctx) or ctx).strip()
445
+ cleaned: list[dict[str, str]] = []
446
+ for it in items:
447
+ if len(cleaned) >= n:
448
+ break
449
+ if not isinstance(it, dict):
450
+ continue
451
+ front = str(it.get("front") or "").strip()
452
+ back = str(it.get("back") or "").strip()
453
+ if not front or not back:
454
+ continue
455
+ ev_raw = str(it.get("evidence") or "").strip()
456
+ evidence = _finalize_evidence(body, ev_raw, front + " " + back, keywords)
457
+ if not evidence:
458
+ continue
459
+ cleaned.append({"front": front, "back": back, "evidence": evidence})
460
+ return cleaned if len(cleaned) >= 1 else None
461
+
462
+
463
+ def _validate_mcq(items: Any, n: int, keywords: set[str], ctx: str, primary_body: str) -> list[dict[str, Any]] | None:
464
+ if not isinstance(items, list):
465
+ return None
466
+ body = (primary_body or _primary_body_from_study_ctx(ctx) or ctx).strip()
467
+ cleaned: list[dict[str, Any]] = []
468
+ for it in items:
469
+ if len(cleaned) >= n:
470
+ break
471
+ if not isinstance(it, dict):
472
+ continue
473
+ q = str(it.get("question") or "").strip()
474
+ opts = it.get("options")
475
+ ai = it.get("answer_index")
476
+ if not q or not isinstance(opts, list) or len(opts) != 4:
477
+ continue
478
+ try:
479
+ ai_i = int(ai)
480
+ except Exception:
481
+ continue
482
+ if ai_i < 0 or ai_i > 3:
483
+ continue
484
+ norm_opts = [str(x or "").strip() for x in opts]
485
+ if any(not o for o in norm_opts):
486
+ continue
487
+ anchor = " ".join([q] + norm_opts)
488
+ ev_raw = str(it.get("evidence") or "").strip()
489
+ evidence = _finalize_evidence(body, ev_raw, anchor, keywords)
490
+ if not evidence:
491
+ continue
492
+ cleaned.append(
493
+ {
494
+ "question": q,
495
+ "options": norm_opts,
496
+ "answer_index": ai_i,
497
+ "evidence": evidence,
498
+ }
499
+ )
500
+ return cleaned if len(cleaned) >= 1 else None
501
+
502
+
503
+ def _coerce_study_list(parsed: Any) -> list | None:
504
+ if isinstance(parsed, list):
505
+ return parsed
506
+ if isinstance(parsed, dict):
507
+ for k in ("items", "flashcards", "cards", "mcq", "mcqs", "questions", "data", "results"):
508
+ v = parsed.get(k)
509
+ if isinstance(v, list):
510
+ return v
511
+ return None
512
+
513
+
514
+ def _synthetic_flashcards_from_body(body: str, n: int) -> list[dict[str, str]]:
515
+ b = (body or "").strip()
516
+ if len(b) < 12:
517
+ return []
518
+ chunks = re.split(r"\n{2,}|(?<=[.!?])\s+", b)
519
+ parts = [p.strip() for p in chunks if len(p.strip()) >= 25]
520
+ out: list[dict[str, str]] = []
521
+ for i in range(0, len(parts), 2):
522
+ if len(out) >= n:
523
+ break
524
+ front = parts[i][:220]
525
+ back = (parts[i + 1] if i + 1 < len(parts) else parts[i])[:400]
526
+ ev = parts[i][: min(180, len(parts[i]))]
527
+ if len(ev) < 12:
528
+ ev = b[:120]
529
+ if len(front) < 3 or len(back) < 3:
530
+ continue
531
+ out.append({"front": front, "back": back, "evidence": ev})
532
+ if not out:
533
+ head = b[: min(400, len(b))]
534
+ ev = b[: min(120, len(b))]
535
+ if len(ev) >= 12:
536
+ out.append({"front": "Notes excerpt", "back": head, "evidence": ev})
537
+ return out[:n]
538
+
539
+
540
+ def _synthetic_mcq_from_body(body: str, n: int) -> list[dict[str, Any]]:
541
+ b = (body or "").strip()
542
+ if len(b) < 12:
543
+ return []
544
+ sentences = [s.strip() for s in re.split(r"[.!?\n]+", b) if len(s.strip()) > 35]
545
+ out: list[dict[str, Any]] = []
546
+ for s in sentences[:n]:
547
+ q = f"Which statement matches the notes? {s[:100]}…"
548
+ o0 = s[: min(90, len(s))] + ("…" if len(s) > 90 else "")
549
+ opts = [
550
+ o0,
551
+ "The notes do not discuss this topic.",
552
+ "The opposite of what the notes state.",
553
+ "None of the above.",
554
+ ]
555
+ ev = s[: min(200, len(s))]
556
+ if len(ev) < 12:
557
+ ev = b[:120]
558
+ out.append({"question": q[:400], "options": opts, "answer_index": 0, "evidence": ev})
559
+ return out
560
+
561
+
562
+ def _synthetic_mind_map(body: str) -> dict[str, Any]:
563
+ b = (body or "").strip()
564
+ lines = [ln.strip() for ln in b.splitlines() if 18 <= len(ln.strip()) <= 220][:14]
565
+ if len(lines) < 2:
566
+ step = 60
567
+ lines = [b[i : i + step].strip() for i in range(0, min(len(b), 480), step) if len(b[i : i + step].strip()) >= 12][
568
+ :10
569
+ ]
570
+ if len(lines) < 2:
571
+ return {"nodes": [], "edges": []}
572
+ nodes = [{"id": str(i + 1), "label": lines[i][:90], "source_quote": lines[i][:220]} for i in range(len(lines))]
573
+ edges = [{"source": str(i), "target": str(i + 1), "label": ""} for i in range(1, len(nodes))]
574
+ return {"nodes": nodes, "edges": edges}
575
+
576
+
577
+ def cheap_study_json(context: str, task: str, n: int) -> tuple[Any, str | None]:
578
+ ctx = context[:60000]
579
+ body = _primary_body_from_study_ctx(ctx)
580
+ keywords = _context_keywords(body or ctx)
581
+ if len(keywords) < 6:
582
+ return None, "Not enough usable note content for grounded study generation."
583
+ if task == "flashcards":
584
+ prompt = f"""You are generating study material ONLY from the provided notes context.
585
+ STRICT RULES:
586
+ - Use only facts/concepts that appear in the context.
587
+ - Do NOT use outside knowledge, generic filler, or random topics.
588
+ - If context is insufficient, still stay within context and produce shorter/simpler cards.
589
+ - Return EXACTLY {n} items.
590
+ - Output ONLY a JSON array of objects with keys "front", "back", "evidence". No markdown fence.
591
+ - "evidence" must be a contiguous quote copied from the PRIMARY FILE CONTENT section (>= 12 chars). Copy punctuation and wording literally when possible.
592
+ - Include exact terminology/phrases from the notes where possible.
593
+
594
+ Notes context:
595
+ {ctx}
596
+ """
597
+ else:
598
+ prompt = f"""You are generating study material ONLY from the provided notes context.
599
+ STRICT RULES:
600
+ - Use only facts/concepts that appear in the context.
601
+ - Do NOT use outside knowledge, generic filler, or random topics.
602
+ - Keep questions grounded in the notes wording/ideas.
603
+ - Return EXACTLY {n} items.
604
+ - Output ONLY a JSON array of objects with keys "question", "options" (array of 4 strings), "answer_index" (0-3), "evidence". No markdown fence.
605
+ - "evidence" must be a contiguous quote copied from the PRIMARY FILE CONTENT section (>= 12 chars). Copy punctuation and wording literally when possible.
606
+ - Include exact terminology/phrases from the notes where possible.
607
+
608
+ Notes context:
609
+ {ctx}
610
+ """
611
+ attempts = 3
612
+ last_err = "generation failed"
613
+ for k in range(attempts):
614
+ msg = prompt if k == 0 else (prompt + "\n\nPrevious output was not grounded in notes. Regenerate with stricter note-anchored content.")
615
+ raw, err = _sarvam_chat_complete(
616
+ [{"role": "user", "content": msg}],
617
+ model=_model_study(),
618
+ max_tokens=8192,
619
+ temperature=0.05,
620
+ )
621
+ if err:
622
+ last_err = err
623
+ continue
624
+ if not raw:
625
+ last_err = "empty model output"
626
+ continue
627
+ try:
628
+ parsed = _parse_json_loose(raw)
629
+ coerced = _coerce_study_list(parsed)
630
+ if coerced is None:
631
+ last_err = "Model returned JSON but not a list of study items."
632
+ continue
633
+ if task == "flashcards":
634
+ valid = _validate_flashcards(coerced, n, keywords, ctx, body)
635
+ else:
636
+ valid = _validate_mcq(coerced, n, keywords, ctx, body)
637
+ if valid is not None and len(valid) >= 1:
638
+ return valid, None
639
+ last_err = "Model output was not grounded in selected notes."
640
+ except json.JSONDecodeError as e:
641
+ last_err = f"invalid JSON: {e}"
642
+ primary = (body or _primary_body_from_study_ctx(ctx) or "").strip()
643
+ if len(primary) >= 12:
644
+ if task == "flashcards":
645
+ syn = _synthetic_flashcards_from_body(primary, n)
646
+ else:
647
+ syn = _synthetic_mcq_from_body(primary, n)
648
+ if syn:
649
+ return syn, None
650
+ return None, last_err
651
+
652
+
653
+ def _prune_mind_map(data: dict, primary_body: str, keywords: set[str]) -> dict | None:
654
+ """Keep nodes grounded in notes; repair or drop bad source_quote; filter edges to kept ids."""
655
+ body = (primary_body or "").strip()
656
+ if len(body) < 12:
657
+ return None
658
+ nodes_raw = data.get("nodes") or []
659
+ edges_raw = data.get("edges") or []
660
+ if not isinstance(nodes_raw, list):
661
+ return None
662
+ kept: list[dict[str, str]] = []
663
+ for n in nodes_raw:
664
+ if not isinstance(n, dict):
665
+ continue
666
+ nid = str(n.get("id") or "").strip()
667
+ label = str(n.get("label") or "").strip()
668
+ quote = str(n.get("source_quote") or "").strip()
669
+ if not nid or not label:
670
+ continue
671
+ final_quote = quote if quote and _contains_context_quote(body, quote) else ""
672
+ if not final_quote:
673
+ final_quote = _pick_evidence_span(body, label + " " + quote)
674
+ if not final_quote or not _contains_context_quote(body, final_quote):
675
+ continue
676
+ kept.append({"id": nid, "label": label, "source_quote": final_quote})
677
+ if len(kept) < 2:
678
+ return None
679
+ kept_ids = {n["id"] for n in kept}
680
+ kept_edges: list[dict[str, str]] = []
681
+ if isinstance(edges_raw, list):
682
+ for e in edges_raw:
683
+ if not isinstance(e, dict):
684
+ continue
685
+ s, t = str(e.get("source") or ""), str(e.get("target") or "")
686
+ if s in kept_ids and t in kept_ids:
687
+ kept_edges.append(
688
+ {
689
+ "source": s,
690
+ "target": t,
691
+ "label": str(e.get("label") or ""),
692
+ }
693
+ )
694
+ return {"nodes": kept, "edges": kept_edges}
695
+
696
+
697
+ def mind_map_json(context: str) -> tuple[dict | None, str | None]:
698
+ ctx = context[:60000]
699
+ body = _primary_body_from_study_ctx(ctx)
700
+ keywords = _context_keywords(body or ctx)
701
+ if len(keywords) < 6:
702
+ return None, "Not enough usable note content for grounded mind map generation."
703
+ prompt = f"""Build a mind map ONLY from the provided notes context.
704
+ STRICT RULES:
705
+ - Use only concepts present in the context.
706
+ - Do NOT add outside topics or generic unrelated nodes.
707
+ - Reuse notes terminology in node labels.
708
+
709
+ Output a single JSON object with:
710
+ "nodes": [ {{"id": string, "label": string, "source_quote": string}} ],
711
+ "edges": [ {{"source": string, "target": string, "label": string}} ]
712
+ Use 8-25 nodes max. IDs must match between edges and nodes. No markdown fence.
713
+ "source_quote" must be a contiguous quote from PRIMARY FILE CONTENT (>= 12 chars).
714
+
715
+ Notes context:
716
+ {ctx}
717
+ """
718
+ last_err = "generation failed"
719
+ for k in range(3):
720
+ msg = prompt if k == 0 else (prompt + "\n\nPrevious output used unrelated topics. Regenerate strictly from notes context.")
721
+ raw, err = _sarvam_chat_complete(
722
+ [{"role": "user", "content": msg}],
723
+ model=_model_study(),
724
+ max_tokens=4096,
725
+ temperature=0.05,
726
+ )
727
+ if err:
728
+ last_err = err
729
+ continue
730
+ if not raw:
731
+ last_err = "empty model output"
732
+ continue
733
+ try:
734
+ data = _parse_json_loose(raw)
735
+ if not isinstance(data, dict):
736
+ last_err = "invalid shape"
737
+ continue
738
+ nodes = data.get("nodes")
739
+ if not isinstance(nodes, list) or not nodes:
740
+ last_err = "invalid shape"
741
+ continue
742
+ pruned = _prune_mind_map(data, body, keywords)
743
+ if pruned is None:
744
+ last_err = "Mind map was not grounded in selected notes."
745
+ continue
746
+ return pruned, None
747
+ except json.JSONDecodeError as e:
748
+ last_err = f"invalid JSON: {e}"
749
+ primary = (body or _primary_body_from_study_ctx(ctx) or "").strip()
750
+ if len(primary) >= 40:
751
+ syn = _synthetic_mind_map(primary)
752
+ if syn.get("nodes") and len(syn["nodes"]) >= 2:
753
+ return syn, None
754
+ return None, last_err
755
+
756
+
backend/onenote_sync.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Microsoft Graph OAuth + OneNote page sync into existing NoteScanner ingest pipeline."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import time
8
+ import uuid
9
+ import html
10
+ from html.parser import HTMLParser
11
+ 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 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"
22
+ GRAPH_TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
23
+ GRAPH_API = "https://graph.microsoft.com/v1.0"
24
+ ONENOTE_SCOPE = "offline_access User.Read Notes.Read"
25
+
26
+
27
+ def is_configured() -> bool:
28
+ return bool((os.getenv("MICROSOFT_CLIENT_ID") or "").strip()) and bool(
29
+ (os.getenv("MICROSOFT_CLIENT_SECRET") or "").strip()
30
+ )
31
+
32
+
33
+ def redirect_uri() -> str:
34
+ return (os.getenv("MICROSOFT_REDIRECT_URI") or "http://localhost:8000/integrations/onenote/callback").strip()
35
+
36
+
37
+ def _client_id() -> str:
38
+ return (os.getenv("MICROSOFT_CLIENT_ID") or "").strip()
39
+
40
+
41
+ def _client_secret() -> str:
42
+ return (os.getenv("MICROSOFT_CLIENT_SECRET") or "").strip()
43
+
44
+
45
+ def build_auth_url(state: str) -> str:
46
+ params = {
47
+ "client_id": _client_id(),
48
+ "response_type": "code",
49
+ "redirect_uri": redirect_uri(),
50
+ "response_mode": "query",
51
+ "scope": ONENOTE_SCOPE,
52
+ "state": state,
53
+ "prompt": "select_account",
54
+ }
55
+ return f"{GRAPH_AUTHORIZE_URL}?{urlencode(params)}"
56
+
57
+
58
+ def _token_request(data: dict) -> dict:
59
+ with httpx.Client(timeout=30.0) as c:
60
+ res = c.post(GRAPH_TOKEN_URL, data=data)
61
+ payload = res.json() if res.headers.get("content-type", "").startswith("application/json") else {}
62
+ if res.status_code >= 400:
63
+ msg = payload.get("error_description") or payload.get("error") or f"HTTP {res.status_code}"
64
+ raise RuntimeError(f"Microsoft token request failed: {msg}")
65
+ return payload
66
+
67
+
68
+ def exchange_code_for_token(code: str) -> dict:
69
+ payload = _token_request(
70
+ {
71
+ "client_id": _client_id(),
72
+ "client_secret": _client_secret(),
73
+ "grant_type": "authorization_code",
74
+ "code": code,
75
+ "redirect_uri": redirect_uri(),
76
+ "scope": ONENOTE_SCOPE,
77
+ }
78
+ )
79
+ expires_in = int(payload.get("expires_in") or 0)
80
+ payload["expires_at"] = int(time.time()) + max(0, expires_in - 30)
81
+ return payload
82
+
83
+
84
+ def refresh_token(token_payload: dict) -> dict:
85
+ rt = (token_payload or {}).get("refresh_token")
86
+ if not rt:
87
+ raise RuntimeError("Missing refresh token.")
88
+ payload = _token_request(
89
+ {
90
+ "client_id": _client_id(),
91
+ "client_secret": _client_secret(),
92
+ "grant_type": "refresh_token",
93
+ "refresh_token": rt,
94
+ "redirect_uri": redirect_uri(),
95
+ "scope": ONENOTE_SCOPE,
96
+ }
97
+ )
98
+ expires_in = int(payload.get("expires_in") or 0)
99
+ payload["expires_at"] = int(time.time()) + max(0, expires_in - 30)
100
+ return payload
101
+
102
+
103
+ def ensure_user_access_token(user_id: str) -> tuple[str, dict]:
104
+ tok = onenote_token_get(user_id)
105
+ if not tok:
106
+ raise RuntimeError("OneNote is not connected. Authorize Microsoft first.")
107
+ if int(tok.get("expires_at") or 0) <= int(time.time()):
108
+ tok = refresh_token(tok)
109
+ onenote_token_upsert(user_id, tok)
110
+ at = (tok.get("access_token") or "").strip()
111
+ if not at:
112
+ raise RuntimeError("Missing access token. Reconnect OneNote.")
113
+ return at, tok
114
+
115
+
116
+ class _HTMLToText(HTMLParser):
117
+ def __init__(self):
118
+ super().__init__()
119
+ self.parts: list[str] = []
120
+
121
+ def handle_data(self, data):
122
+ if data:
123
+ self.parts.append(data)
124
+
125
+ def handle_starttag(self, tag, attrs):
126
+ if tag in {"br", "p", "div", "li", "tr", "h1", "h2", "h3", "h4"}:
127
+ self.parts.append("\n")
128
+
129
+ def handle_endtag(self, tag):
130
+ if tag in {"p", "div", "li", "tr"}:
131
+ self.parts.append("\n")
132
+
133
+ def text(self) -> str:
134
+ raw = "".join(self.parts)
135
+ raw = html.unescape(raw)
136
+ raw = re.sub(r"\r\n?", "\n", raw)
137
+ raw = re.sub(r"\n{3,}", "\n\n", raw)
138
+ return raw.strip()
139
+
140
+
141
+ def _safe_name(name: str) -> str:
142
+ n = (name or "").strip()
143
+ n = re.sub(r"[^\w\-. ]+", "_", n, flags=re.UNICODE).strip(" ._")
144
+ return n or "untitled"
145
+
146
+
147
+ def _graph_get_json(url: str, access_token: str) -> dict:
148
+ with httpx.Client(timeout=45.0) as c:
149
+ res = c.get(url, headers={"Authorization": f"Bearer {access_token}"})
150
+ payload = res.json() if res.headers.get("content-type", "").startswith("application/json") else {}
151
+ if res.status_code >= 400:
152
+ msg = payload.get("error", {}).get("message") or f"HTTP {res.status_code}"
153
+ raise RuntimeError(f"Microsoft Graph request failed: {msg}")
154
+ return payload if isinstance(payload, dict) else {}
155
+
156
+
157
+ def _graph_get_text(url: str, access_token: str) -> str:
158
+ with httpx.Client(timeout=45.0) as c:
159
+ res = c.get(url, headers={"Authorization": f"Bearer {access_token}"})
160
+ if res.status_code >= 400:
161
+ raise RuntimeError(f"Failed to fetch OneNote page content (HTTP {res.status_code}).")
162
+ return res.text or ""
163
+
164
+
165
+ def _list_onenote_pages(access_token: str, max_pages: int) -> list[dict]:
166
+ top = max(1, min(int(max_pages), 100))
167
+ # Pull notebook and section names so we can map pages under course-like folders.
168
+ url = (
169
+ f"{GRAPH_API}/me/onenote/pages"
170
+ f"?$top={top}"
171
+ "&$select=id,title,lastModifiedDateTime,contentUrl"
172
+ "&$expand=parentSection($select=displayName,parentNotebook;"
173
+ "$expand=parentNotebook($select=displayName))"
174
+ "&$orderby=lastModifiedDateTime desc"
175
+ )
176
+ data = _graph_get_json(url, access_token)
177
+ vals = data.get("value") or []
178
+ return [x for x in vals if isinstance(x, dict)]
179
+
180
+
181
+ def _page_to_rel_path(page: dict) -> tuple[str, str]:
182
+ title = _safe_name(str(page.get("title") or "OneNote page"))
183
+ pid = str(page.get("id") or uuid.uuid4().hex)
184
+ section = (page.get("parentSection") or {}) if isinstance(page.get("parentSection"), dict) else {}
185
+ notebook = (section.get("parentNotebook") or {}) if isinstance(section.get("parentNotebook"), dict) else {}
186
+ course = _safe_name(str(notebook.get("displayName") or section.get("displayName") or "OneNote"))
187
+ filename = f"{title}-{pid[:8]}.txt"
188
+ rel_path = f"{course}/{filename}".replace("\\", "/")
189
+ return rel_path, title
190
+
191
+
192
+ def sync_onenote_pages_to_ingest(user_id: str, max_pages: int = 25) -> dict:
193
+ access_token, _ = ensure_user_access_token(user_id)
194
+ pages = _list_onenote_pages(access_token, max_pages=max_pages)
195
+ tree = vfs_get_tree(user_id)
196
+ ingested = 0
197
+ skipped = 0
198
+ errors: list[str] = []
199
+
200
+ for page in pages:
201
+ try:
202
+ content_url = str(page.get("contentUrl") or "").strip()
203
+ if not content_url:
204
+ skipped += 1
205
+ continue
206
+ rel_path, source_title = _page_to_rel_path(page)
207
+ html_doc = _graph_get_text(content_url, access_token)
208
+ parser = _HTMLToText()
209
+ parser.feed(html_doc)
210
+ text = parser.text()
211
+ if not text:
212
+ skipped += 1
213
+ continue
214
+ folder = rel_path.rsplit("/", 1)[0]
215
+ file_name = rel_path.rsplit("/", 1)[-1]
216
+ tree = tree_add_folder(tree, "", folder)
217
+ tree = tree_add_file(tree, folder, file_name)
218
+ try:
219
+ user_document_upsert(user_id, rel_path, text, source_title)
220
+ except Exception:
221
+ # user_documents is a cache; ingest chunks are the primary retrieval source.
222
+ pass
223
+ ingest_text_for_path(user_id, rel_path, source_title, text)
224
+ ingested += 1
225
+ except Exception as e:
226
+ errors.append(str(e))
227
+ continue
228
+
229
+ vfs_set_tree(user_id, tree)
230
+ return {
231
+ "pages_seen": len(pages),
232
+ "pages_ingested": ingested,
233
+ "pages_skipped": skipped,
234
+ "errors": errors[:10],
235
+ }
236
+
backend/vfs_tree.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Virtual folder tree mutations (explorer). Stored in ChromaDB, not on disk."""
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ from typing import Any
6
+
7
+
8
+ def _norm(p: str) -> str:
9
+ return (p or "").replace("\\", "/").strip("/")
10
+
11
+
12
+ def tree_has_folder(tree: list, folder_path: str) -> bool:
13
+ """True if folder_path exists as a folder in the tree (empty path = root)."""
14
+ fp = _norm(folder_path)
15
+ if not fp:
16
+ return True
17
+ parts = [x for x in fp.split("/") if x]
18
+ cur = tree
19
+ for part in parts:
20
+ found = None
21
+ for n in cur:
22
+ if n.get("type") == "folder" and n.get("name") == part:
23
+ found = n
24
+ break
25
+ if not found:
26
+ return False
27
+ cur = found.get("children") or []
28
+ return True
29
+
30
+
31
+ def join_rel(parent: str, name: str) -> str:
32
+ p = _norm(parent)
33
+ return f"{p}/{name}" if p else name
34
+
35
+
36
+ def ensure_folder_chain(tree: list, parent_path: str) -> list:
37
+ """Return the children list under parent_path (create folders as needed)."""
38
+ if not _norm(parent_path):
39
+ return tree
40
+ parts = [x for x in _norm(parent_path).split("/") if x]
41
+ cur = tree
42
+ acc: list[str] = []
43
+ for part in parts:
44
+ acc.append(part)
45
+ full = "/".join(acc)
46
+ found = None
47
+ for node in cur:
48
+ if node.get("type") == "folder" and node.get("name") == part:
49
+ found = node
50
+ break
51
+ if not found:
52
+ new_f: dict[str, Any] = {"type": "folder", "name": part, "path": full, "children": []}
53
+ cur.append(new_f)
54
+ found = new_f
55
+ cur = found.setdefault("children", [])
56
+ return cur
57
+
58
+
59
+ def tree_add_folder(tree: list, parent_path: str, name: str) -> list:
60
+ t = copy.deepcopy(tree)
61
+ children = ensure_folder_chain(t, parent_path)
62
+ full = join_rel(parent_path, name)
63
+ if any(n.get("path") == full for n in children):
64
+ return t
65
+ children.append({"type": "folder", "name": name, "path": full, "children": []})
66
+ return t
67
+
68
+
69
+ def tree_add_file(tree: list, parent_path: str, filename: str) -> list:
70
+ t = copy.deepcopy(tree)
71
+ children = ensure_folder_chain(t, parent_path)
72
+ full = join_rel(parent_path, filename)
73
+ full = full.replace("\\", "/")
74
+ if any(n.get("path") == full for n in children):
75
+ return t
76
+ children.append({"type": "file", "name": filename, "path": full})
77
+ return t
78
+
79
+
80
+ def tree_remove_path(tree: list, target_path: str) -> list:
81
+ """Remove a file, or a folder and everything under it."""
82
+ tp = _norm(target_path)
83
+
84
+ def rec(nodes: list) -> list:
85
+ out: list = []
86
+ for n in nodes:
87
+ p = _norm(n.get("path") or "")
88
+ if n.get("type") == "folder":
89
+ if p == tp or p.startswith(tp + "/"):
90
+ continue
91
+ out.append({**n, "children": rec(n.get("children") or [])})
92
+ else:
93
+ if p == tp or p.startswith(tp + "/"):
94
+ continue
95
+ out.append(n)
96
+ return out
97
+
98
+ return rec(copy.deepcopy(tree))
99
+
100
+
101
+ def tree_move_path(tree: list, from_path: str, to_folder: str, new_name: str | None = None) -> list:
102
+ """
103
+ Move a file or folder subtree. to_folder is destination directory ("" = root).
104
+ new_name optional rename (basename of root of moved subtree).
105
+ """
106
+ fp = _norm(from_path)
107
+ dest_parent = _norm(to_folder)
108
+ removed: dict | None = None
109
+
110
+ def extract(nodes: list) -> list:
111
+ nonlocal removed
112
+ out = []
113
+ for n in nodes:
114
+ p = _norm(n.get("path") or "")
115
+ if n.get("type") == "folder":
116
+ if p == fp:
117
+ removed = copy.deepcopy(n)
118
+ continue
119
+ out.append({**n, "children": extract(n.get("children") or [])})
120
+ else:
121
+ if p == fp:
122
+ removed = copy.deepcopy(n)
123
+ continue
124
+ out.append(n)
125
+ return out
126
+
127
+ t = extract(copy.deepcopy(tree))
128
+ if not removed:
129
+ return copy.deepcopy(tree)
130
+
131
+ old_root = _norm(removed["path"])
132
+ nm = new_name or removed["name"]
133
+ new_root = join_rel(dest_parent, nm)
134
+
135
+ def rebase(n: dict) -> dict:
136
+ n = copy.deepcopy(n)
137
+ p = _norm(n["path"])
138
+ if p == old_root:
139
+ n["path"] = new_root
140
+ elif p.startswith(old_root + "/"):
141
+ n["path"] = new_root + "/" + p[len(old_root) + 1 :]
142
+ if n.get("type") == "folder":
143
+ n["children"] = [rebase(c) for c in n.get("children") or []]
144
+ return n
145
+
146
+ rebased = rebase(removed)
147
+ children = ensure_folder_chain(t, dest_parent)
148
+ children.append(rebased)
149
+ return t
150
+
151
+
152
+ def flatten_file_paths(tree: list) -> list[str]:
153
+ out: list[str] = []
154
+
155
+ def walk(nodes: list) -> None:
156
+ for n in nodes:
157
+ if n.get("type") == "folder":
158
+ walk(n.get("children") or [])
159
+ else:
160
+ p = (n.get("path") or "").replace("\\", "/")
161
+ if p:
162
+ out.append(p)
163
+
164
+ walk(tree)
165
+ return out
docker-compose.yml ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: "3.9"
2
+ services:
3
+ # Omit or stop this service if you use Chroma Cloud (CHROMA_API_KEY in .env).
4
+ chromadb:
5
+ image: chromadb/chroma
6
+ container_name: notescanner-chromadb
7
+ ports:
8
+ - "8100:8000"
9
+ volumes:
10
+ - chroma_data:/chroma/chroma
11
+
12
+ backend:
13
+ build: .
14
+ container_name: notescanner-backend
15
+ depends_on:
16
+ - chromadb
17
+ env_file:
18
+ - .env
19
+ environment:
20
+ - CHROMA_HOST=chromadb
21
+ - CHROMA_PORT=8000
22
+ ports:
23
+ - "8000:8000"
24
+ command: ["uvicorn", "backend.api:app", "--host", "0.0.0.0", "--port", "8000"]
25
+
26
+ frontend:
27
+ build:
28
+ context: ./frontend/my-app
29
+ dockerfile: Dockerfile
30
+ container_name: notescanner-frontend
31
+ depends_on:
32
+ - backend
33
+ ports:
34
+ - "5173:5173"
35
+ volumes:
36
+ - ./frontend/my-app/src:/app/src
37
+ - ./frontend/my-app/public:/app/public
38
+ - ./frontend/my-app/index.html:/app/index.html
39
+ - ./frontend/my-app/vite.config.js:/app/vite.config.js
40
+ command: ["npm", "run", "dev", "--", "--host"]
41
+
42
+ volumes:
43
+ chroma_data:
frontend/my-app/.dockerignore ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ node_modules
2
+ npm-debug.log
3
+ .git
4
+ .gitignore
5
+ README.md
6
+ .env
7
+ .nyc_output
8
+ coverage
9
+ .DS_Store
10
+ *.log
11
+
frontend/my-app/.gitignore ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Logs
2
+ logs
3
+ *.log
4
+ npm-debug.log*
5
+ yarn-debug.log*
6
+ yarn-error.log*
7
+ pnpm-debug.log*
8
+ lerna-debug.log*
9
+
10
+ node_modules
11
+ dist
12
+ dist-ssr
13
+ *.local
14
+
15
+ # Editor directories and files
16
+ .vscode/*
17
+ !.vscode/extensions.json
18
+ .idea
19
+ .DS_Store
20
+ *.suo
21
+ *.ntvs*
22
+ *.njsproj
23
+ *.sln
24
+ *.sw?
frontend/my-app/Dockerfile ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM arm64v8/node:20-bookworm-slim
2
+
3
+ RUN npm install -g npm@latest
4
+
5
+ WORKDIR /app
6
+
7
+ COPY package*.json ./
8
+
9
+ RUN rm -rf node_modules package-lock.json && \
10
+ npm cache clean --force && \
11
+ npm install --legacy-peer-deps --platform=linux --arch=arm64 --no-audit --no-fund
12
+
13
+ RUN npm install --platform=linux --arch=arm64 @rollup/rollup-linux-arm64-gnu --no-audit --no-fund
14
+
15
+ COPY . .
16
+
17
+ RUN chown -R node:node /app
18
+ USER node
19
+
20
+ EXPOSE 5173
21
+
22
+ CMD ["npm", "run", "dev", "--", "--host"]
frontend/my-app/eslint.config.js ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import js from '@eslint/js'
2
+ import globals from 'globals'
3
+ import reactHooks from 'eslint-plugin-react-hooks'
4
+ import reactRefresh from 'eslint-plugin-react-refresh'
5
+ import { defineConfig, globalIgnores } from 'eslint/config'
6
+
7
+ export default defineConfig([
8
+ globalIgnores(['dist']),
9
+ {
10
+ files: ['**/*.{js,jsx}'],
11
+ extends: [
12
+ js.configs.recommended,
13
+ reactHooks.configs['recommended-latest'],
14
+ reactRefresh.configs.vite,
15
+ ],
16
+ languageOptions: {
17
+ ecmaVersion: 2020,
18
+ globals: globals.browser,
19
+ parserOptions: {
20
+ ecmaVersion: 'latest',
21
+ ecmaFeatures: { jsx: true },
22
+ sourceType: 'module',
23
+ },
24
+ },
25
+ rules: {
26
+ 'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
27
+ },
28
+ },
29
+ ])
frontend/my-app/index.html ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>NoteScanner</title>
7
+ </head>
8
+ <body>
9
+ <div id="root"></div>
10
+ <script type="module" src="/src/main.jsx"></script>
11
+ </body>
12
+ </html>
frontend/my-app/package.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "my-app",
3
+ "private": true,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "build": "vite build",
9
+ "lint": "eslint .",
10
+ "preview": "vite preview"
11
+ },
12
+ "dependencies": {
13
+ "@xyflow/react": "^12.10.2",
14
+ "react": "^19.1.1",
15
+ "react-dom": "^19.1.1",
16
+ "react-icons": "^5.5.0"
17
+ },
18
+ "devDependencies": {
19
+ "@eslint/js": "^9.35.0",
20
+ "@types/react": "^19.1.13",
21
+ "@types/react-dom": "^19.1.9",
22
+ "@vitejs/plugin-react": "^5.0.2",
23
+ "eslint": "^9.35.0",
24
+ "eslint-plugin-react-hooks": "^5.2.0",
25
+ "eslint-plugin-react-refresh": "^0.4.20",
26
+ "globals": "^16.4.0",
27
+ "vite": "^7.1.6"
28
+ }
29
+ }
frontend/my-app/src/App.jsx ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useCallback, useEffect } from "react";
2
+ import { getSessionId, removeSession, ensureGuestId, isSignedIn } from "./auth";
3
+ import Login from "./pages/Login";
4
+ import Register from "./pages/Register";
5
+ import Home from "./pages/Home";
6
+ import ChatPage from "./pages/ChatPage";
7
+
8
+ function App() {
9
+ const [signedIn, setSignedIn] = useState(isSignedIn());
10
+ const [authView, setAuthView] = useState(null);
11
+
12
+ useEffect(() => {
13
+ if (!getSessionId()) ensureGuestId();
14
+ }, []);
15
+
16
+ const onLogin = useCallback(() => {
17
+ setSignedIn(true);
18
+ setAuthView(null);
19
+ }, []);
20
+
21
+ const onLogout = useCallback(() => {
22
+ removeSession();
23
+ setSignedIn(false);
24
+ ensureGuestId();
25
+ }, []);
26
+
27
+ const openSignIn = useCallback(() => setAuthView("login"), []);
28
+ const openSignUp = useCallback(() => setAuthView("register"), []);
29
+
30
+ return (
31
+ <>
32
+ {signedIn ? (
33
+ <Home
34
+ onLogout={onLogout}
35
+ onSignInClick={openSignIn}
36
+ signedIn={signedIn}
37
+ />
38
+ ) : (
39
+ <ChatPage onSignInClick={openSignIn} />
40
+ )}
41
+ {authView === "login" && (
42
+ <div className="auth-overlay" onClick={() => setAuthView(null)}>
43
+ <div className="auth-overlay-content" onClick={(e) => e.stopPropagation()}>
44
+ <Login
45
+ onLogin={onLogin}
46
+ onSwitchToRegister={() => setAuthView("register")}
47
+ onClose={() => setAuthView(null)}
48
+ />
49
+ </div>
50
+ </div>
51
+ )}
52
+ {authView === "register" && (
53
+ <div className="auth-overlay" onClick={() => setAuthView(null)}>
54
+ <div className="auth-overlay-content" onClick={(e) => e.stopPropagation()}>
55
+ <Register
56
+ onRegister={onLogin}
57
+ onSwitchToLogin={() => setAuthView("login")}
58
+ onClose={() => setAuthView(null)}
59
+ />
60
+ </div>
61
+ </div>
62
+ )}
63
+ </>
64
+ );
65
+ }
66
+
67
+ export default App;
frontend/my-app/src/auth.js ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { API_BASE } from "./config";
2
+ import { getBlobUrlForPath } from "./localFileStore";
3
+
4
+ const SESSION_KEY = "notescanner_session_id";
5
+ const GUEST_KEY = "notescanner_guest_id";
6
+ const USER_NAME_KEY = "notescanner_user_name";
7
+ const SESSION_HEADER = "X-Session-Id";
8
+ const GUEST_HEADER = "X-Guest-Id";
9
+
10
+ export function getSessionId() {
11
+ return localStorage.getItem(SESSION_KEY);
12
+ }
13
+
14
+ export function setSessionId(sessionId, userName = null) {
15
+ localStorage.setItem(SESSION_KEY, sessionId);
16
+ localStorage.removeItem(GUEST_KEY);
17
+ if (userName != null) localStorage.setItem(USER_NAME_KEY, userName);
18
+ }
19
+
20
+ export function removeSession() {
21
+ localStorage.removeItem(SESSION_KEY);
22
+ localStorage.removeItem(USER_NAME_KEY);
23
+ }
24
+
25
+ export function getUserName() {
26
+ return localStorage.getItem(USER_NAME_KEY) || "";
27
+ }
28
+
29
+ export function setUserName(name) {
30
+ if (name != null) localStorage.setItem(USER_NAME_KEY, name);
31
+ }
32
+
33
+ export function getGuestId() {
34
+ return localStorage.getItem(GUEST_KEY);
35
+ }
36
+
37
+ export function setGuestId(guestId) {
38
+ localStorage.setItem(GUEST_KEY, guestId);
39
+ }
40
+
41
+ const _apiBase = () => API_BASE || "http://localhost:8000";
42
+
43
+ /** Ensure we have a guest id (fetch from backend if missing). Returns a promise that resolves when ready. */
44
+ export async function ensureGuestId() {
45
+ if (getSessionId()) return;
46
+ let g = getGuestId();
47
+ if (!g) {
48
+ const res = await fetch(`${_apiBase()}/guest_id`);
49
+ let data = {};
50
+ try {
51
+ data = await res.json();
52
+ } catch (_) {}
53
+ if (data.guest_id) {
54
+ setGuestId(data.guest_id);
55
+ g = data.guest_id;
56
+ }
57
+ }
58
+ return g;
59
+ }
60
+
61
+ export function getAuthHeadersForFetch() {
62
+ const sessionId = getSessionId();
63
+ if (sessionId) return { [SESSION_HEADER]: sessionId };
64
+ const guestId = getGuestId();
65
+ if (guestId) return { [GUEST_HEADER]: guestId };
66
+ return {};
67
+ }
68
+
69
+ /** Blob URL for a path if this device has a local copy (e.g. after upload). Server does not store binaries. */
70
+ export function getFileUrl(path) {
71
+ return getBlobUrlForPath(path) || "";
72
+ }
73
+
74
+ export function authFetch(url, options = {}) {
75
+ const headers = { ...getAuthHeadersForFetch(), ...options.headers };
76
+ return fetch(url, { ...options, headers });
77
+ }
78
+
79
+ /** Readable string from FastAPI/JSON error bodies (detail, error, message). */
80
+ export function apiErrorMessage(data, res) {
81
+ const status = res?.status;
82
+ if (!data || typeof data !== "object") {
83
+ return status ? `Request failed (HTTP ${status})` : "Request failed";
84
+ }
85
+ if (typeof data.detail === "string" && data.detail) return data.detail;
86
+ if (Array.isArray(data.detail) && data.detail.length) {
87
+ const parts = data.detail.map((x) =>
88
+ x && typeof x === "object" && x.msg != null ? String(x.msg) : String(x),
89
+ );
90
+ const joined = parts.join("; ").trim();
91
+ if (joined) return joined;
92
+ }
93
+ if (data.error) return String(data.error);
94
+ if (data.message) return String(data.message);
95
+ return status ? `Request failed (HTTP ${status})` : "Request failed";
96
+ }
97
+
98
+ export function isSignedIn() {
99
+ return !!getSessionId();
100
+ }
frontend/my-app/src/components/Explorer.jsx ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useState, useRef } from "react";
2
+ import {
3
+ VscNewFile,
4
+ VscNewFolder,
5
+ VscRefresh,
6
+ VscCollapseAll,
7
+ } from "react-icons/vsc";
8
+ import { BsFileEarmarkPdf } from "react-icons/bs";
9
+ import FileUpload from "./FileUpload";
10
+ import { API_BASE } from "../config";
11
+ import { authFetch, getFileUrl, ensureGuestId } from "../auth";
12
+ import {
13
+ forgetPath,
14
+ forgetPathPrefix,
15
+ relocateLocalEntry,
16
+ } from "../localFileStore";
17
+ import {
18
+ isOpfsMirrorSupported,
19
+ isUserFolderPickerSupported,
20
+ hasUserDiskRootLinkedSync,
21
+ loadStoredRootHandle,
22
+ linkNoteScannerFolder,
23
+ ensurePersistentStoragePermission,
24
+ withNotesRoot,
25
+ mirrorEnsureDir,
26
+ mirrorWriteFile,
27
+ mirrorRemove,
28
+ mirrorMoveFile,
29
+ mirrorMoveFolder,
30
+ } from "../localDiskFolder";
31
+ import { sanitizeVirtualPath } from "../virtualPath";
32
+
33
+ // ─── Icons ───────────────────────────────────────────────────────────────────
34
+
35
+ function FileTypeIcon({ name, size = 16 }) {
36
+ const ext = name.includes(".") ? name.split(".").pop().toLowerCase() : "";
37
+ const isPdf = ext === "pdf";
38
+ const isImage = ["png","jpg","jpeg","gif","webp","bmp","tiff","svg"].includes(ext);
39
+ const isText = ["txt","md","json","xml","csv","log"].includes(ext);
40
+
41
+ if (isPdf) return (
42
+ <span className="vsc2-file-icon vsc2-icon-pdf"><BsFileEarmarkPdf size={size} /></span>
43
+ );
44
+ if (isImage) return (
45
+ <span className="vsc2-file-icon vsc2-icon-image">
46
+ <svg viewBox="0 0 16 16" width={size} height={size} fill="currentColor">
47
+ <path d="M14 2H2c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm0 11H2V3h12v10zM4 10l2-2 2 2 2-3 3 4H4z"/>
48
+ </svg>
49
+ </span>
50
+ );
51
+ if (isText) return (
52
+ <span className="vsc2-file-icon vsc2-icon-text">
53
+ <svg viewBox="0 0 16 16" width={size} height={size} fill="currentColor">
54
+ <path d="M3 2h10a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1zm1 2v1h8V4H4zm0 3v1h8V7H4zm0 3v1h5v-1H4z"/>
55
+ </svg>
56
+ </span>
57
+ );
58
+ return (
59
+ <span className="vsc2-file-icon vsc2-icon-default">
60
+ <svg viewBox="0 0 16 16" width={size} height={size} fill="currentColor">
61
+ <path d="M10 1H3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h10c.55 0 1-.45 1-1V5L10 1zm1 12H3V2h6v4h4v7z"/>
62
+ </svg>
63
+ </span>
64
+ );
65
+ }
66
+
67
+ // ─── Main Component ───────────────────────────────────────────────────────────
68
+
69
+ export default function Explorer({
70
+ onFileSelect,
71
+ onDeletePath,
72
+ onMovePath,
73
+ onTreeChange,
74
+ }) {
75
+ const [tree, setTree] = useState([]);
76
+ const [expandedFolders, setExpandedFolders] = useState(new Set());
77
+ const [selectedItem, setSelectedItem] = useState(null);
78
+ const [selectedIsFolder, setSelectedIsFolder] = useState(false);
79
+ /** 'folder' | 'file' | null */
80
+ const [createInputMode, setCreateInputMode] = useState(null);
81
+ const [createInputValue, setCreateInputValue] = useState("");
82
+ const [dragSource, setDragSource] = useState(null);
83
+ const [dropTarget, setDropTarget] = useState(null);
84
+ const [newFileMenuOpen, setNewFileMenuOpen] = useState(false);
85
+ const [ctxMenu, setCtxMenu] = useState(null);
86
+ const fileInputRef = useRef(null);
87
+ const createInputRef = useRef(null);
88
+ const createRowRef = useRef(null);
89
+ const newFileMenuWrapRef = useRef(null);
90
+
91
+ useEffect(() => {
92
+ if (!isUserFolderPickerSupported() && isOpfsMirrorSupported()) {
93
+ void ensurePersistentStoragePermission();
94
+ }
95
+ }, []);
96
+
97
+ /** Restore localStorage linked-flag from IndexedDB (e.g. after deploy) so we don’t show the picker again. */
98
+ useEffect(() => {
99
+ void loadStoredRootHandle();
100
+ }, []);
101
+
102
+ const fetchTree = async () => {
103
+ const res = await authFetch(`${API_BASE}/list_tree`);
104
+ const data = await res.json();
105
+ setTree(data.tree || []);
106
+ onTreeChange?.();
107
+ };
108
+
109
+ useEffect(() => {
110
+ ensureGuestId().then(() => fetchTree());
111
+ }, []);
112
+
113
+ useEffect(() => {
114
+ if (!createInputMode) return;
115
+ const handleClickOutside = (e) => {
116
+ if (createRowRef.current && !createRowRef.current.contains(e.target)) {
117
+ setCreateInputMode(null);
118
+ setCreateInputValue("");
119
+ }
120
+ };
121
+ document.addEventListener("mousedown", handleClickOutside);
122
+ return () => document.removeEventListener("mousedown", handleClickOutside);
123
+ }, [createInputMode]);
124
+
125
+ useEffect(() => {
126
+ if (!newFileMenuOpen) return;
127
+ const close = (e) => {
128
+ if (newFileMenuWrapRef.current && !newFileMenuWrapRef.current.contains(e.target)) {
129
+ setNewFileMenuOpen(false);
130
+ }
131
+ };
132
+ document.addEventListener("mousedown", close);
133
+ return () => document.removeEventListener("mousedown", close);
134
+ }, [newFileMenuOpen]);
135
+
136
+ useEffect(() => {
137
+ if (!ctxMenu) return;
138
+ const close = (e) => {
139
+ if (e?.target?.closest?.(".vsc2-context-menu")) return;
140
+ setCtxMenu(null);
141
+ };
142
+ const onKey = (e) => {
143
+ if (e.key === "Escape") setCtxMenu(null);
144
+ };
145
+ document.addEventListener("mousedown", close);
146
+ document.addEventListener("keydown", onKey);
147
+ return () => {
148
+ document.removeEventListener("mousedown", close);
149
+ document.removeEventListener("keydown", onKey);
150
+ };
151
+ }, [ctxMenu]);
152
+
153
+ const openContextMenu = (e, node) => {
154
+ e.preventDefault();
155
+ e.stopPropagation();
156
+ setCtxMenu({ x: e.clientX, y: e.clientY, node });
157
+ };
158
+
159
+ const copyNodePath = async (node) => {
160
+ const p = node.path.replace(/\\/g, "/");
161
+ try {
162
+ await navigator.clipboard.writeText(p);
163
+ } catch {
164
+ try {
165
+ const ta = document.createElement("textarea");
166
+ ta.value = p;
167
+ ta.style.position = "fixed";
168
+ ta.style.left = "-9999px";
169
+ document.body.appendChild(ta);
170
+ ta.select();
171
+ document.execCommand("copy");
172
+ document.body.removeChild(ta);
173
+ } catch {
174
+ alert("Could not copy path.");
175
+ }
176
+ }
177
+ setCtxMenu(null);
178
+ };
179
+
180
+ const clearTreeSelection = () => {
181
+ setSelectedItem(null);
182
+ setSelectedIsFolder(false);
183
+ };
184
+
185
+ const handleTreeMouseDown = (e) => {
186
+ if (e.target.closest(".vsc2-row")) return;
187
+ clearTreeSelection();
188
+ };
189
+
190
+ const toggleFolder = (folderPath) => {
191
+ setExpandedFolders((prev) => {
192
+ const next = new Set(prev);
193
+ next.has(folderPath) ? next.delete(folderPath) : next.add(folderPath);
194
+ return next;
195
+ });
196
+ };
197
+
198
+ const parentPathForCreate = selectedIsFolder && selectedItem
199
+ ? selectedItem
200
+ : selectedItem && !selectedIsFolder
201
+ ? selectedItem.replace(/\/[^/]+$/, "")
202
+ : "";
203
+
204
+ const openCreateFolderInput = () => {
205
+ setCreateInputValue("");
206
+ setCreateInputMode("folder");
207
+ setTimeout(() => createInputRef.current?.focus(), 0);
208
+ };
209
+
210
+ const openCreateFileInput = () => {
211
+ setCreateInputValue("");
212
+ setCreateInputMode("file");
213
+ setTimeout(() => createInputRef.current?.focus(), 0);
214
+ };
215
+
216
+ const collapseAllFolders = () => {
217
+ setExpandedFolders(new Set());
218
+ };
219
+
220
+ const submitCreateInput = async () => {
221
+ const name = createInputValue.trim();
222
+ if (!name) return;
223
+ const mode = createInputMode;
224
+ const parentForCreate = parentPathForCreate;
225
+
226
+ // Must not await IndexedDB before showDirectoryPicker — that drops user activation and the picker never opens.
227
+ if (mode === "folder" && !parentForCreate && isUserFolderPickerSupported() && !hasUserDiskRootLinkedSync()) {
228
+ try {
229
+ const linked = await linkNoteScannerFolder();
230
+ if (linked === null) {
231
+ /* user cancelled setup or wrong folder name — still create the course folder in the app */
232
+ }
233
+ } catch (e) {
234
+ if (e?.name !== "AbortError") {
235
+ alert(e?.message || "Could not link your NoteScanner folder.");
236
+ return;
237
+ }
238
+ }
239
+ }
240
+
241
+ setCreateInputMode(null);
242
+ setCreateInputValue("");
243
+ try {
244
+ const formData = new FormData();
245
+ formData.append("path", sanitizeVirtualPath(parentForCreate));
246
+ formData.append("name", name);
247
+ const url = mode === "folder" ? `${API_BASE}/create_folder` : `${API_BASE}/create_file`;
248
+ const res = await authFetch(url, { method: "POST", body: formData });
249
+ if (res.ok) {
250
+ const data = await res.json().catch(() => ({}));
251
+ const parent = (parentForCreate || "").replace(/\\/g, "/");
252
+ void withNotesRoot(async (root) => {
253
+ if (mode === "folder") {
254
+ const rel = sanitizeVirtualPath(parent ? `${parent}/${name}` : name);
255
+ await mirrorEnsureDir(root, rel);
256
+ } else {
257
+ const rel = sanitizeVirtualPath(data.path || "");
258
+ if (rel) await mirrorWriteFile(root, rel, new Blob([]));
259
+ }
260
+ });
261
+ fetchTree();
262
+ setExpandedFolders((prev) => {
263
+ const n = new Set(prev);
264
+ const parent = (parentForCreate || "").replace(/\\/g, "/");
265
+ if (parent) n.add(parent);
266
+ if (mode === "folder") {
267
+ const rel = parent ? `${parent}/${name}` : name.replace(/\\/g, "/");
268
+ n.add(rel);
269
+ }
270
+ return n;
271
+ });
272
+ } else {
273
+ const data = await res.json().catch(() => ({}));
274
+ alert(data.error || `Failed to create ${mode === "folder" ? "folder" : "file"}.`);
275
+ }
276
+ } catch {
277
+ alert(`Failed to create ${mode === "folder" ? "folder" : "file"}.`);
278
+ }
279
+ };
280
+
281
+ const handleMove = async (fromPath, toFolder) => {
282
+ if (!fromPath || toFolder === undefined) return;
283
+ if (toFolder === fromPath || (fromPath + "/").startsWith(toFolder + "/")) return;
284
+ try {
285
+ const formData = new FormData();
286
+ formData.append("from_path", sanitizeVirtualPath(fromPath));
287
+ formData.append("to_folder", sanitizeVirtualPath(toFolder));
288
+ const res = await authFetch(`${API_BASE}/move_path`, { method: "POST", body: formData });
289
+ if (res.ok) {
290
+ const data = await res.json().catch(() => ({}));
291
+ const toPath = (data.path || "").replace(/\\/g, "/").replace(/^\/+/, "");
292
+ if (toPath) {
293
+ relocateLocalEntry(fromPath, toPath, !!dragSource.isFolder);
294
+ onMovePath?.(fromPath, toPath, !!dragSource.isFolder);
295
+ const isFolder = !!dragSource.isFolder;
296
+ void withNotesRoot((root) =>
297
+ isFolder
298
+ ? mirrorMoveFolder(root, fromPath, toPath)
299
+ : mirrorMoveFile(root, fromPath, toPath),
300
+ );
301
+ }
302
+ fetchTree();
303
+ } else {
304
+ const data = await res.json().catch(() => ({}));
305
+ alert(data.error || "Move failed.");
306
+ }
307
+ } catch {
308
+ alert("Move failed.");
309
+ } finally {
310
+ setDragSource(null);
311
+ setDropTarget(null);
312
+ }
313
+ };
314
+
315
+ const deleteNode = async (node) => {
316
+ const isFolder = node.type === "folder";
317
+ if (!window.confirm(isFolder ? `Delete folder "${node.name}" and all its contents?` : `Delete file "${node.name}"?`)) return;
318
+ setCtxMenu(null);
319
+ const formData = new FormData();
320
+ formData.append("path", sanitizeVirtualPath(node.path));
321
+ formData.append("kind", isFolder ? "folder" : "file");
322
+ const res = await authFetch(`${API_BASE}/delete_path`, { method: "POST", body: formData });
323
+ if (res.ok) {
324
+ if (isFolder) forgetPathPrefix(node.path);
325
+ else forgetPath(node.path);
326
+ void withNotesRoot((root) => mirrorRemove(root, node.path, isFolder));
327
+ onDeletePath?.(node.path, isFolder);
328
+ fetchTree();
329
+ } else {
330
+ const data = await res.json().catch(() => ({}));
331
+ alert(data.error || "Delete failed.");
332
+ }
333
+ };
334
+ const canDropOn = (targetFolderPath) => {
335
+ if (!dragSource) return false;
336
+ if (targetFolderPath === dragSource.path) return false;
337
+ if (dragSource.isFolder && (targetFolderPath + "/").startsWith(dragSource.path + "/")) return false;
338
+ return true;
339
+ };
340
+
341
+ // ─── Recursive tree renderer ─────────────────────────────────────────────
342
+
343
+ const renderNode = (node, depth = 0, parentLines = []) => {
344
+ const INDENT = 8; // px per depth level (matches VS Code's tight spacing)
345
+
346
+ if (node.type === "folder") {
347
+ const isExpanded = expandedFolders.has(node.path);
348
+ const isDropTarget = dropTarget === node.path && canDropOn(node.path);
349
+ const isSelected = selectedItem === node.path;
350
+
351
+ return (
352
+ <div key={node.path} className="vsc2-node">
353
+ <div
354
+ className={`vsc2-row${isSelected ? " vsc2-row--selected" : ""}${isDropTarget ? " vsc2-row--drop" : ""}`}
355
+ style={{ paddingLeft: `${depth * INDENT + 4}px` }}
356
+ onClick={() => {
357
+ setSelectedItem(node.path);
358
+ setSelectedIsFolder(true);
359
+ toggleFolder(node.path);
360
+ }}
361
+ draggable
362
+ onDragStart={(e) => {
363
+ setDragSource({ path: node.path, isFolder: true });
364
+ e.dataTransfer.setData("text/plain", node.path);
365
+ e.dataTransfer.effectAllowed = "move";
366
+ }}
367
+ onDragOver={(e) => {
368
+ e.preventDefault();
369
+ e.dataTransfer.dropEffect = "move";
370
+ if (canDropOn(node.path)) setDropTarget(node.path);
371
+ }}
372
+ onDragLeave={() => setDropTarget((t) => (t === node.path ? null : t))}
373
+ onDrop={(e) => {
374
+ e.preventDefault();
375
+ if (dropTarget === node.path && dragSource) handleMove(dragSource.path, node.path);
376
+ setDropTarget(null);
377
+ }}
378
+ onDragEnd={() => { setDragSource(null); setDropTarget(null); }}
379
+ >
380
+ {/* Indent guides */}
381
+ {Array.from({ length: depth }).map((_, i) => (
382
+ <span
383
+ key={i}
384
+ className="vsc2-indent-guide"
385
+ style={{ left: `${i * INDENT + 8}px` }}
386
+ />
387
+ ))}
388
+
389
+ <span
390
+ className="vsc2-row-name-hit"
391
+ onContextMenu={(e) => openContextMenu(e, node)}
392
+ >
393
+ <span className={`vsc2-chevron${isExpanded ? " vsc2-chevron--open" : ""}`}>
394
+ <svg viewBox="0 0 16 16" width="16" height="16" fill="currentColor" aria-hidden>
395
+ <path d="M6 4l4 4-4 4V4Z" />
396
+ </svg>
397
+ </span>
398
+ <span className="vsc2-label">{node.name}</span>
399
+ </span>
400
+ </div>
401
+
402
+ {isExpanded && (
403
+ <div className="vsc2-children">
404
+ {(node.children || []).map((child) =>
405
+ renderNode(child, depth + 1, [...parentLines])
406
+ )}
407
+ </div>
408
+ )}
409
+ </div>
410
+ );
411
+ }
412
+
413
+ // File row
414
+ const isSelected = selectedItem === node.path;
415
+ return (
416
+ <div
417
+ key={node.path}
418
+ className={`vsc2-row vsc2-row--file${isSelected ? " vsc2-row--selected" : ""}`}
419
+ style={{ paddingLeft: `${depth * INDENT + 4 + 16}px` }} /* +16 for chevron space */
420
+ onClick={() => {
421
+ setSelectedItem(node.path);
422
+ setSelectedIsFolder(false);
423
+ onFileSelect?.(getFileUrl(node.path) || null, node.name, node.path);
424
+ }}
425
+ draggable
426
+ onDragStart={(e) => {
427
+ setDragSource({ path: node.path, isFolder: false });
428
+ e.dataTransfer.setData("text/plain", node.path);
429
+ e.dataTransfer.effectAllowed = "move";
430
+ }}
431
+ onDragEnd={() => { setDragSource(null); setDropTarget(null); }}
432
+ >
433
+ {/* Indent guides for files */}
434
+ {Array.from({ length: depth }).map((_, i) => (
435
+ <span
436
+ key={i}
437
+ className="vsc2-indent-guide"
438
+ style={{ left: `${i * INDENT + 8}px` }}
439
+ />
440
+ ))}
441
+
442
+ <span className="vsc2-row-name-hit" onContextMenu={(e) => openContextMenu(e, node)}>
443
+ <FileTypeIcon name={node.name} size={15} />
444
+ <span className="vsc2-label">{node.name}</span>
445
+ </span>
446
+ </div>
447
+ );
448
+ };
449
+
450
+ const uploadPath = selectedIsFolder && selectedItem ? selectedItem : "";
451
+
452
+ return (
453
+ <div className="vsc2-explorer">
454
+ {/* Header — VS Code–style title + toolbar */}
455
+ <div className="vsc2-header">
456
+ <span
457
+ className="vsc2-header-title"
458
+ onClick={clearTreeSelection}
459
+ onKeyDown={(e) => {
460
+ if (e.key === "Enter" || e.key === " ") {
461
+ e.preventDefault();
462
+ clearTreeSelection();
463
+ }
464
+ }}
465
+ role="button"
466
+ tabIndex={0}
467
+ title="Clear selection — new folder/file goes to workspace root"
468
+ >
469
+ NOTESCANNER
470
+ </span>
471
+ <div className="vsc2-header-actions">
472
+ <div className="vsc2-header-menu-wrap" ref={newFileMenuWrapRef}>
473
+ <button
474
+ type="button"
475
+ className="vsc2-header-btn"
476
+ onClick={() => setNewFileMenuOpen((o) => !o)}
477
+ title="New file or upload"
478
+ aria-expanded={newFileMenuOpen}
479
+ aria-haspopup="menu"
480
+ aria-label="New file or upload"
481
+ >
482
+ <VscNewFile size={16} />
483
+ </button>
484
+ {newFileMenuOpen && (
485
+ <div className="vsc2-dropdown" role="menu">
486
+ <button
487
+ type="button"
488
+ className="vsc2-dropdown-item"
489
+ role="menuitem"
490
+ onClick={() => {
491
+ setNewFileMenuOpen(false);
492
+ openCreateFileInput();
493
+ }}
494
+ >
495
+ New empty file…
496
+ </button>
497
+ <button
498
+ type="button"
499
+ className="vsc2-dropdown-item"
500
+ role="menuitem"
501
+ onClick={() => {
502
+ setNewFileMenuOpen(false);
503
+ fileInputRef.current?.click();
504
+ }}
505
+ >
506
+ Upload file…
507
+ </button>
508
+ </div>
509
+ )}
510
+ </div>
511
+ <button
512
+ type="button"
513
+ className="vsc2-header-btn"
514
+ onClick={openCreateFolderInput}
515
+ title="New Folder"
516
+ aria-label="New Folder"
517
+ >
518
+ <VscNewFolder size={16} />
519
+ </button>
520
+ <button
521
+ type="button"
522
+ className="vsc2-header-btn"
523
+ onClick={() => fetchTree()}
524
+ title="Refresh Explorer"
525
+ aria-label="Refresh Explorer"
526
+ >
527
+ <VscRefresh size={16} />
528
+ </button>
529
+ <button
530
+ type="button"
531
+ className="vsc2-header-btn"
532
+ onClick={collapseAllFolders}
533
+ title="Collapse Folders in Explorer"
534
+ aria-label="Collapse Folders in Explorer"
535
+ >
536
+ <VscCollapseAll size={16} />
537
+ </button>
538
+ </div>
539
+ </div>
540
+
541
+ {createInputMode && (
542
+ <div className="vsc2-create-row" ref={createRowRef}>
543
+ <input
544
+ ref={createInputRef}
545
+ type="text"
546
+ className="vsc2-create-input"
547
+ placeholder={
548
+ createInputMode === "folder"
549
+ ? (parentPathForCreate ? `New folder in ${parentPathForCreate}` : "New folder name…")
550
+ : (parentPathForCreate ? `New file in ${parentPathForCreate} (e.g. notes.txt)` : "New file name (e.g. notes.txt)")
551
+ }
552
+ value={createInputValue}
553
+ onChange={(e) => setCreateInputValue(e.target.value)}
554
+ onKeyDown={(e) => {
555
+ if (e.key === "Enter") submitCreateInput();
556
+ if (e.key === "Escape") {
557
+ setCreateInputMode(null);
558
+ setCreateInputValue("");
559
+ }
560
+ }}
561
+ />
562
+ <button
563
+ type="button"
564
+ className="vsc2-create-btn"
565
+ onClick={submitCreateInput}
566
+ disabled={!createInputValue.trim()}
567
+ >
568
+ OK
569
+ </button>
570
+ </div>
571
+ )}
572
+
573
+ <FileUpload ref={fileInputRef} path={uploadPath} onFileUploaded={fetchTree} hidden />
574
+
575
+ {ctxMenu && (
576
+ <div
577
+ className="vsc2-context-menu"
578
+ style={{ left: ctxMenu.x, top: ctxMenu.y }}
579
+ role="menu"
580
+ >
581
+ <button
582
+ type="button"
583
+ className="vsc2-context-menu-item"
584
+ role="menuitem"
585
+ onClick={() => copyNodePath(ctxMenu.node)}
586
+ >
587
+ Copy path
588
+ </button>
589
+ <button
590
+ type="button"
591
+ className="vsc2-context-menu-item vsc2-context-menu-item--danger"
592
+ role="menuitem"
593
+ onClick={() => deleteNode(ctxMenu.node)}
594
+ >
595
+ Delete…
596
+ </button>
597
+ </div>
598
+ )}
599
+
600
+ <div className="vsc2-tree" onMouseDown={handleTreeMouseDown}>
601
+ {dragSource && (
602
+ <div
603
+ className={`vsc2-root-drop${dropTarget === "" ? " vsc2-row--drop" : ""}`}
604
+ onDragOver={(e) => { e.preventDefault(); setDropTarget(""); }}
605
+ onDragLeave={() => setDropTarget((t) => (t === "" ? null : t))}
606
+ onDrop={(e) => { e.preventDefault(); if (dragSource) handleMove(dragSource.path, ""); setDropTarget(null); }}
607
+ >
608
+ Move to root
609
+ </div>
610
+ )}
611
+
612
+ {tree.length === 0 ? (
613
+ <div className="vsc2-empty">No files yet. Use New File or New Folder (click the title above to target the root).</div>
614
+ ) : (
615
+ tree.map((node) => renderNode(node, 0))
616
+ )}
617
+ </div>
618
+ </div>
619
+ );
620
+ }
frontend/my-app/src/components/FileUpload.jsx ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, forwardRef } from "react";
2
+ import { API_BASE } from "../config";
3
+ import { authFetch, apiErrorMessage } from "../auth";
4
+ import { registerLocalFile } from "../localFileStore";
5
+ import { getNotesMirrorRoot, mirrorUploadedBytes } from "../localDiskFolder";
6
+ import { sanitizeVirtualPath } from "../virtualPath";
7
+
8
+ const FileUpload = forwardRef(function FileUpload(
9
+ { path, onFileUploaded, hidden = false },
10
+ ref
11
+ ) {
12
+ const [uploading, setUploading] = useState(false);
13
+
14
+ const doUpload = async (file) => {
15
+ if (!file) return;
16
+
17
+ const formData = new FormData();
18
+ formData.append("path", sanitizeVirtualPath(path));
19
+ formData.append("file", file);
20
+ formData.append("auto_extract", "true");
21
+
22
+ try {
23
+ setUploading(true);
24
+ // Resolve folder permission before the network round-trip (keeps user activation useful).
25
+ const { root: mirrorRoot } = await getNotesMirrorRoot();
26
+
27
+ const res = await authFetch(`${API_BASE}/upload_note`, {
28
+ method: "POST",
29
+ body: formData,
30
+ });
31
+
32
+ const result = await res.json().catch(() => ({}));
33
+ const rel = sanitizeVirtualPath(result.path || "");
34
+ if (rel && file) {
35
+ registerLocalFile(rel, file);
36
+ try {
37
+ await mirrorUploadedBytes(file, rel, mirrorRoot);
38
+ } catch (mirrorErr) {
39
+ console.error("Local mirror write failed:", mirrorErr);
40
+ }
41
+ }
42
+
43
+ if (res.ok) {
44
+ onFileUploaded?.(result, file);
45
+ } else {
46
+ alert(`Error: ${apiErrorMessage(result, res)}`);
47
+ }
48
+ } catch (error) {
49
+ console.error("Upload error:", error);
50
+ alert(
51
+ error?.message?.includes("fetch")
52
+ ? "Upload failed: could not reach the backend. Is it running (e.g. http://localhost:8000)?"
53
+ : `Upload failed: ${error?.message || "Network error"}`,
54
+ );
55
+ } finally {
56
+ setUploading(false);
57
+ }
58
+ };
59
+
60
+ const handleChange = async (e) => {
61
+ const file = e.target.files?.[0];
62
+ if (file) {
63
+ await doUpload(file);
64
+ }
65
+ e.target.value = "";
66
+ };
67
+
68
+ if (hidden) {
69
+ return (
70
+ <input
71
+ ref={ref}
72
+ type="file"
73
+ accept="image/*,.pdf,.txt,.md,.csv,.json"
74
+ onChange={handleChange}
75
+ style={{ display: "none" }}
76
+ disabled={uploading}
77
+ aria-hidden
78
+ />
79
+ );
80
+ }
81
+
82
+ return (
83
+ <div className="folder-form">
84
+ <input
85
+ ref={ref}
86
+ type="file"
87
+ accept="image/*,.pdf,.txt,.md,.csv,.json"
88
+ onChange={handleChange}
89
+ />
90
+ </div>
91
+ );
92
+ });
93
+
94
+ export default FileUpload;
frontend/my-app/src/components/QueryInterface.jsx ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useRef, useEffect } from "react";
2
+ import { LuSendHorizontal, LuPlus, LuMic, LuRotateCcw } from "react-icons/lu";
3
+ import { API_BASE } from "../config";
4
+ import { authFetch } from "../auth";
5
+
6
+ export default function QueryInterface({
7
+ coursesCsv = "",
8
+ activeFilePath = "",
9
+ activeCourseFolder = "",
10
+ }) {
11
+ const makeSessionId = () =>
12
+ (typeof crypto !== "undefined" && crypto.randomUUID
13
+ ? crypto.randomUUID()
14
+ : `${Date.now()}-${Math.random().toString(36).slice(2)}`);
15
+ const [query, setQuery] = useState("");
16
+ const [messages, setMessages] = useState([]);
17
+ const [loading, setLoading] = useState(false);
18
+ const [listening, setListening] = useState(false);
19
+ const [chatSessionId, setChatSessionId] = useState(makeSessionId);
20
+ const messagesEndRef = useRef(null);
21
+ const uploadInputRef = useRef(null);
22
+ const recognitionRef = useRef(null);
23
+
24
+ const scrollToBottom = () => {
25
+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
26
+ };
27
+ useEffect(() => {
28
+ scrollToBottom();
29
+ }, [messages]);
30
+
31
+ useEffect(() => {
32
+ return () => {
33
+ if (recognitionRef.current) {
34
+ recognitionRef.current.stop();
35
+ recognitionRef.current = null;
36
+ }
37
+ const fd = new FormData();
38
+ fd.append("chat_session_id", chatSessionId);
39
+ authFetch(`${API_BASE}/chat/session/clear`, { method: "POST", body: fd }).catch(() => {});
40
+ };
41
+ }, [chatSessionId]);
42
+
43
+ const handleUpload = async (file) => {
44
+ if (!file) return;
45
+ const formData = new FormData();
46
+ formData.append("chat_session_id", chatSessionId);
47
+ formData.append("file", file);
48
+ const res = await authFetch(`${API_BASE}/chat/upload_ephemeral`, {
49
+ method: "POST",
50
+ body: formData,
51
+ });
52
+ const data = await res.json().catch(() => ({}));
53
+ if (!res.ok) {
54
+ throw new Error(data.detail || data.error || "Upload failed.");
55
+ }
56
+ const chars = data?.text_chars;
57
+ const suffix = Number.isFinite(chars) ? ` (${chars} chars cached)` : "";
58
+ setMessages((prev) => [
59
+ ...prev,
60
+ { role: "assistant", content: `Uploaded ${file.name} for this chat session${suffix}.` },
61
+ ]);
62
+ };
63
+
64
+ const handleVoiceInput = () => {
65
+ const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
66
+ if (!SpeechRecognition) {
67
+ setMessages((prev) => [
68
+ ...prev,
69
+ { role: "assistant", content: "Voice input is not supported in this browser." },
70
+ ]);
71
+ return;
72
+ }
73
+ if (listening && recognitionRef.current) {
74
+ recognitionRef.current.stop();
75
+ return;
76
+ }
77
+ const rec = new SpeechRecognition();
78
+ rec.lang = "en-US";
79
+ rec.interimResults = false;
80
+ rec.maxAlternatives = 1;
81
+ rec.onstart = () => setListening(true);
82
+ rec.onresult = (event) => {
83
+ const spoken = event?.results?.[0]?.[0]?.transcript || "";
84
+ if (spoken.trim()) {
85
+ setQuery((prev) => (prev ? `${prev} ${spoken}` : spoken));
86
+ }
87
+ };
88
+ rec.onerror = () => setListening(false);
89
+ rec.onend = () => {
90
+ setListening(false);
91
+ recognitionRef.current = null;
92
+ };
93
+ recognitionRef.current = rec;
94
+ rec.start();
95
+ };
96
+
97
+ const handleSubmit = async (e) => {
98
+ e.preventDefault();
99
+ const text = query.trim();
100
+ if (!text) return;
101
+
102
+ setQuery("");
103
+ setMessages((prev) => [...prev, { role: "user", content: text }]);
104
+ setLoading(true);
105
+
106
+ try {
107
+ const includeCourseByPrompt = /\b(course notes|other notes|same course|all notes|include course|include other)\b/i.test(text);
108
+ const formData = new FormData();
109
+ formData.append("query", text);
110
+ formData.append("subject", "");
111
+ formData.append("courses", coursesCsv);
112
+ formData.append("opened_file_path", activeFilePath || "");
113
+ formData.append("course_path", activeCourseFolder || "");
114
+ formData.append("include_course_context", includeCourseByPrompt ? "true" : "false");
115
+ formData.append("use_course_notes", includeCourseByPrompt ? "true" : "false");
116
+ formData.append("chat_session_id", chatSessionId);
117
+
118
+ const res = await authFetch(`${API_BASE}/query_folder`, {
119
+ method: "POST",
120
+ body: formData,
121
+ });
122
+
123
+ const data = await res.json().catch(() => ({}));
124
+ const errMsg = data.detail || data.error;
125
+ const answer = res.ok && !errMsg
126
+ ? data.answer
127
+ : (errMsg ? `Error: ${errMsg}` : "Query failed. Please try again.");
128
+ const source_documents = data.source_documents || [];
129
+
130
+ setMessages((prev) => [
131
+ ...prev,
132
+ {
133
+ role: "assistant",
134
+ content: answer,
135
+ source_documents,
136
+ },
137
+ ]);
138
+ } catch (err) {
139
+ console.error("Query error:", err);
140
+ setMessages((prev) => [
141
+ ...prev,
142
+ { role: "assistant", content: "Query failed. Please try again.", source_documents: [] },
143
+ ]);
144
+ } finally {
145
+ setLoading(false);
146
+ }
147
+ };
148
+
149
+ return (
150
+ <div className="query-interface">
151
+ <div className="query-messages">
152
+ {messages.length === 0 && (
153
+ <div className="query-messages-empty">Ask a question about your notes.</div>
154
+ )}
155
+ {messages.map((msg, index) => (
156
+ <div key={index} className={`query-message query-message--${msg.role}`}>
157
+ <div className="query-message-bubble">
158
+ <div className="query-message-content">{msg.content}</div>
159
+ {msg.role === "assistant" && msg.source_documents?.length > 0 ? (
160
+ <div className="query-sources">
161
+ <div className="query-sources-title">Sources</div>
162
+ {msg.source_documents.map((doc, i) => (
163
+ <div key={i} className="query-source-item">
164
+ <div className="query-source-meta">
165
+ {(doc.metadata?.source_file || doc.metadata?.path || "chunk") +
166
+ (doc.metadata?.is_primary_authority ? " · primary" : "")}
167
+ </div>
168
+ {doc.content?.substring(0, 200)}…
169
+ </div>
170
+ ))}
171
+ </div>
172
+ ) : null}
173
+ </div>
174
+ </div>
175
+ ))}
176
+ {loading && (
177
+ <div className="query-message query-message--assistant">
178
+ <div className="query-message-bubble query-message-loading">
179
+ <div className="query-message-content">Thinking…</div>
180
+ </div>
181
+ </div>
182
+ )}
183
+ <div ref={messagesEndRef} />
184
+ </div>
185
+
186
+ <form onSubmit={handleSubmit} className="query-form query-form-bottom">
187
+ <label className="query-form-label-sr">Query your notes</label>
188
+ <div className="query-input-wrap">
189
+ <button
190
+ type="button"
191
+ className="query-input-icon"
192
+ title="Add files/images"
193
+ aria-label="Add files/images"
194
+ onClick={() => uploadInputRef.current?.click()}
195
+ disabled={loading}
196
+ >
197
+ <LuPlus size={18} />
198
+ </button>
199
+ <textarea
200
+ value={query}
201
+ onChange={(e) => setQuery(e.target.value)}
202
+ onKeyDown={(e) => {
203
+ if (e.key === "Enter" && !e.shiftKey) {
204
+ e.preventDefault();
205
+ if (query.trim()) handleSubmit(e);
206
+ }
207
+ }}
208
+ placeholder="Query your notes"
209
+ rows={1}
210
+ className="query-form-textarea query-form-textarea-inline"
211
+ disabled={loading}
212
+ aria-label="Query your notes"
213
+ />
214
+ <button
215
+ type="button"
216
+ className={`query-input-icon ${listening ? "query-input-icon--active" : ""}`}
217
+ title={listening ? "Stop voice input" : "Voice input"}
218
+ aria-label={listening ? "Stop voice input" : "Voice input"}
219
+ onClick={handleVoiceInput}
220
+ disabled={loading}
221
+ >
222
+ <LuMic size={18} />
223
+ </button>
224
+ <button
225
+ type="button"
226
+ className="query-input-icon"
227
+ title="Refresh chat"
228
+ aria-label="Refresh chat"
229
+ onClick={async () => {
230
+ const fd = new FormData();
231
+ fd.append("chat_session_id", chatSessionId);
232
+ await authFetch(`${API_BASE}/chat/session/clear`, { method: "POST", body: fd }).catch(() => {});
233
+ setMessages([]);
234
+ setChatSessionId(makeSessionId());
235
+ }}
236
+ disabled={loading}
237
+ >
238
+ <LuRotateCcw size={18} />
239
+ </button>
240
+ <button
241
+ type="submit"
242
+ disabled={loading || !query.trim()}
243
+ className="query-submit-icon"
244
+ title="Send"
245
+ aria-label="Send query"
246
+ >
247
+ <LuSendHorizontal size={20} />
248
+ </button>
249
+ </div>
250
+ </form>
251
+ <input
252
+ ref={uploadInputRef}
253
+ type="file"
254
+ accept="image/*,.pdf,.txt,.md,.csv,.json"
255
+ style={{ display: "none" }}
256
+ onChange={async (e) => {
257
+ const file = e.target.files?.[0];
258
+ e.target.value = "";
259
+ if (!file) return;
260
+ try {
261
+ await handleUpload(file);
262
+ } catch (err) {
263
+ setMessages((prev) => [
264
+ ...prev,
265
+ { role: "assistant", content: `Upload failed: ${err?.message || "Unknown error."}` },
266
+ ]);
267
+ }
268
+ }}
269
+ />
270
+ </div>
271
+ );
272
+ }
frontend/my-app/src/components/StudyPanel.jsx ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useCallback } from "react";
2
+ import {
3
+ ReactFlow,
4
+ Background,
5
+ Controls,
6
+ useNodesState,
7
+ useEdgesState,
8
+ ReactFlowProvider,
9
+ } from "@xyflow/react";
10
+ import "@xyflow/react/dist/style.css";
11
+ import { API_BASE } from "../config";
12
+ import { authFetch } from "../auth";
13
+
14
+ function graphToFlow(graph) {
15
+ const rawNodes = graph?.nodes || [];
16
+ const nodes = rawNodes.map((n, i) => ({
17
+ id: String(n.id),
18
+ position: { x: (i % 6) * 140, y: Math.floor(i / 6) * 100 },
19
+ data: { label: n.label || n.id },
20
+ }));
21
+ const edges = (graph?.edges || []).map((e, i) => ({
22
+ id: `e${i}`,
23
+ source: String(e.source),
24
+ target: String(e.target),
25
+ label: e.label || "",
26
+ }));
27
+ return { initialNodes: nodes, initialEdges: edges };
28
+ }
29
+
30
+ export default function StudyPanel({
31
+ coursesCsv = "",
32
+ activeFilePath = "",
33
+ activeCourseFolder = "",
34
+ }) {
35
+ const [tab, setTab] = useState("flashcards");
36
+ const [loading, setLoading] = useState(false);
37
+ const [error, setError] = useState("");
38
+ const [cards, setCards] = useState([]);
39
+ const [cardIdx, setCardIdx] = useState(0);
40
+ const [showBack, setShowBack] = useState(false);
41
+ const [mcq, setMcq] = useState([]);
42
+ const [mcqIdx, setMcqIdx] = useState(0);
43
+ const [picked, setPicked] = useState(null);
44
+ const [nodes, setNodes, onNodesChange] = useNodesState([]);
45
+ const [edges, setEdges, onEdgesChange] = useEdgesState([]);
46
+ const hasActiveFile = !!(activeFilePath || "").trim();
47
+
48
+ const runFlashcards = useCallback(async () => {
49
+ setLoading(true);
50
+ setError("");
51
+ setCards([]);
52
+ setCardIdx(0);
53
+ setShowBack(false);
54
+ try {
55
+ const fd = new FormData();
56
+ fd.append("task", "flashcards");
57
+ fd.append("count", "8");
58
+ fd.append("courses", coursesCsv);
59
+ fd.append("opened_file_path", activeFilePath || "");
60
+ fd.append("course_path", activeCourseFolder || "");
61
+ fd.append("include_course_context", "true");
62
+ fd.append("focus_query", "important definitions and exam topics");
63
+ const res = await authFetch(`${API_BASE}/study/generate`, { method: "POST", body: fd });
64
+ const data = await res.json().catch(() => ({}));
65
+ if (!res.ok) throw new Error(data.error || "Failed");
66
+ const raw = Array.isArray(data.items) ? data.items : [];
67
+ const items = raw.filter(
68
+ (x) => x && typeof x.front === "string" && typeof x.back === "string"
69
+ );
70
+ if (!items.length) throw new Error("No flashcards returned for this file.");
71
+ setCards(items);
72
+ setCardIdx(0);
73
+ setShowBack(false);
74
+ } catch (e) {
75
+ setError(e.message || "Failed");
76
+ setCards([]);
77
+ } finally {
78
+ setLoading(false);
79
+ }
80
+ }, [coursesCsv, activeFilePath, activeCourseFolder]);
81
+
82
+ const runMcq = useCallback(async () => {
83
+ setLoading(true);
84
+ setError("");
85
+ setMcq([]);
86
+ setMcqIdx(0);
87
+ setPicked(null);
88
+ try {
89
+ const fd = new FormData();
90
+ fd.append("task", "mcq");
91
+ fd.append("count", "5");
92
+ fd.append("courses", coursesCsv);
93
+ fd.append("opened_file_path", activeFilePath || "");
94
+ fd.append("course_path", activeCourseFolder || "");
95
+ fd.append("include_course_context", "true");
96
+ fd.append("focus_query", "practice exam style");
97
+ const res = await authFetch(`${API_BASE}/study/generate`, { method: "POST", body: fd });
98
+ const data = await res.json().catch(() => ({}));
99
+ if (!res.ok) throw new Error(data.error || "Failed");
100
+ const raw = Array.isArray(data.items) ? data.items : [];
101
+ const items = raw.filter(
102
+ (x) =>
103
+ x &&
104
+ typeof x.question === "string" &&
105
+ Array.isArray(x.options) &&
106
+ x.options.length >= 2
107
+ );
108
+ if (!items.length) throw new Error("No MCQs returned for this file.");
109
+ setMcq(items);
110
+ setMcqIdx(0);
111
+ setPicked(null);
112
+ } catch (e) {
113
+ setError(e.message || "Failed");
114
+ setMcq([]);
115
+ } finally {
116
+ setLoading(false);
117
+ }
118
+ }, [coursesCsv, activeFilePath, activeCourseFolder]);
119
+
120
+ const runMindmap = useCallback(async () => {
121
+ setLoading(true);
122
+ setError("");
123
+ setNodes([]);
124
+ setEdges([]);
125
+ try {
126
+ const fd = new FormData();
127
+ fd.append("courses", coursesCsv);
128
+ fd.append("opened_file_path", activeFilePath || "");
129
+ fd.append("course_path", activeCourseFolder || "");
130
+ fd.append("include_course_context", "true");
131
+ fd.append("focus_query", "concept relationships");
132
+ const res = await authFetch(`${API_BASE}/study/mindmap`, { method: "POST", body: fd });
133
+ const data = await res.json().catch(() => ({}));
134
+ if (!res.ok) throw new Error(data.error || "Failed");
135
+ const nodesRaw = Array.isArray(data?.graph?.nodes) ? data.graph.nodes : [];
136
+ if (!nodesRaw.length) throw new Error("No mind map returned for this file.");
137
+ const graph = {
138
+ ...data.graph,
139
+ nodes: nodesRaw.map((n) => {
140
+ if (!n || typeof n.label !== "string") return n;
141
+ const sq = typeof n.source_quote === "string" ? n.source_quote.trim() : "";
142
+ const label = n.label.trim();
143
+ return {
144
+ ...n,
145
+ source_quote: sq.length >= 8 ? sq : label.slice(0, 220),
146
+ };
147
+ }),
148
+ };
149
+ const { initialNodes, initialEdges } = graphToFlow(graph);
150
+ setNodes(initialNodes);
151
+ setEdges(initialEdges);
152
+ } catch (e) {
153
+ setError(e.message || "Failed");
154
+ setNodes([]);
155
+ setEdges([]);
156
+ } finally {
157
+ setLoading(false);
158
+ }
159
+ }, [coursesCsv, activeFilePath, activeCourseFolder, setNodes, setEdges]);
160
+
161
+ return (
162
+ <ReactFlowProvider>
163
+ <div className="study-panel">
164
+ <div className="study-tabs">
165
+ <button type="button" className={tab === "flashcards" ? "active" : ""} onClick={() => setTab("flashcards")}>
166
+ Flashcards
167
+ </button>
168
+ <button type="button" className={tab === "mcq" ? "active" : ""} onClick={() => setTab("mcq")}>
169
+ Mock MCQ
170
+ </button>
171
+ <button type="button" className={tab === "map" ? "active" : ""} onClick={() => setTab("map")}>
172
+ Mind map
173
+ </button>
174
+ </div>
175
+ {error && <div className="study-error">{error}</div>}
176
+ {tab === "flashcards" && (
177
+ <div className="study-section">
178
+ <button type="button" className="study-action" disabled={loading || !hasActiveFile} onClick={runFlashcards}>
179
+ {loading ? "…" : "Generate flashcards"}
180
+ </button>
181
+ {cards.length > 0 && (
182
+ <div className="flashcard">
183
+ <div className="flashcard-index">
184
+ {cardIdx + 1} / {cards.length}
185
+ </div>
186
+ <button type="button" className="flashcard-face" onClick={() => setShowBack((s) => !s)}>
187
+ {showBack ? cards[cardIdx]?.back : cards[cardIdx]?.front}
188
+ </button>
189
+ <div className="flashcard-nav">
190
+ <button type="button" disabled={cardIdx <= 0} onClick={() => { setCardIdx((i) => i - 1); setShowBack(false); }}>
191
+ Prev
192
+ </button>
193
+ <button type="button" disabled={cardIdx >= cards.length - 1} onClick={() => { setCardIdx((i) => i + 1); setShowBack(false); }}>
194
+ Next
195
+ </button>
196
+ </div>
197
+ </div>
198
+ )}
199
+ </div>
200
+ )}
201
+ {tab === "mcq" && (
202
+ <div className="study-section">
203
+ <button type="button" className="study-action" disabled={loading || !hasActiveFile} onClick={runMcq}>
204
+ {loading ? "…" : "Generate MCQ"}
205
+ </button>
206
+ {mcq.length > 0 && (
207
+ <div className="mcq-block">
208
+ <p className="mcq-q">{mcq[mcqIdx]?.question}</p>
209
+ <ul className="mcq-options">
210
+ {(mcq[mcqIdx]?.options || []).map((opt, i) => (
211
+ <li key={i}>
212
+ <button type="button" className={picked === i ? "picked" : ""} onClick={() => setPicked(i)}>
213
+ {opt}
214
+ </button>
215
+ </li>
216
+ ))}
217
+ </ul>
218
+ {picked != null && (
219
+ <p className="mcq-ans">
220
+ {picked === mcq[mcqIdx]?.answer_index ? "Correct." : `Answer: option ${(mcq[mcqIdx]?.answer_index ?? 0) + 1}`}
221
+ </p>
222
+ )}
223
+ <div className="flashcard-nav">
224
+ <button type="button" disabled={mcqIdx <= 0} onClick={() => { setMcqIdx((i) => i - 1); setPicked(null); }}>
225
+ Prev
226
+ </button>
227
+ <button type="button" disabled={mcqIdx >= mcq.length - 1} onClick={() => { setMcqIdx((i) => i + 1); setPicked(null); }}>
228
+ Next
229
+ </button>
230
+ </div>
231
+ </div>
232
+ )}
233
+ </div>
234
+ )}
235
+ {tab === "map" && (
236
+ <div className="study-section study-map-wrap">
237
+ <button type="button" className="study-action" disabled={loading || !hasActiveFile} onClick={runMindmap}>
238
+ {loading ? "…" : "Build mind map"}
239
+ </button>
240
+ <div className="react-flow-wrap">
241
+ <ReactFlow nodes={nodes} edges={edges} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} fitView>
242
+ <Background />
243
+ <Controls />
244
+ </ReactFlow>
245
+ </div>
246
+ </div>
247
+ )}
248
+ </div>
249
+ </ReactFlowProvider>
250
+ );
251
+ }
frontend/my-app/src/config.js ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * API base URL for the NoteScanner backend.
3
+ * - VITE_API_URL (if set) wins.
4
+ * - In dev or when opened from localhost: http://localhost:8000.
5
+ * - In production (non-localhost): same origin unless VITE_API_URL is set.
6
+ */
7
+ function getDefaultApiBase() {
8
+ if (import.meta.env.VITE_API_URL) return import.meta.env.VITE_API_URL;
9
+ if (import.meta.env.DEV) return "http://localhost:8000";
10
+ if (typeof window !== "undefined" && window.location?.hostname === "localhost") return "http://localhost:8000";
11
+ return "";
12
+ }
13
+ // Use getter so that when bundle runs in browser (e.g. localhost), we get the right default
14
+ export const API_BASE = typeof window !== "undefined" ? getDefaultApiBase() : (import.meta.env.VITE_API_URL || "");
frontend/my-app/src/index.css ADDED
@@ -0,0 +1,1135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ─── Reset ─────────────────────────────────────────────────────────────── */
2
+ * { margin: 0; padding: 0; box-sizing: border-box; }
3
+ html, body { height: 100%; overflow: hidden; }
4
+
5
+ /* ─── Auth (Login / Register) ───────────────────────────────────────────── */
6
+ .auth-page {
7
+ display: flex;
8
+ align-items: center;
9
+ justify-content: center;
10
+ padding: 0;
11
+ }
12
+ .auth-card {
13
+ position: relative;
14
+ width: 100%;
15
+ max-width: 360px;
16
+ background: #252526;
17
+ border: 1px solid #3c3c3c;
18
+ border-radius: 8px;
19
+ padding: 2rem;
20
+ }
21
+ .auth-title {
22
+ font-size: 1.5rem;
23
+ color: #cccccc;
24
+ margin-bottom: 0.25rem;
25
+ text-align: center;
26
+ }
27
+ .auth-subtitle {
28
+ font-size: 0.9rem;
29
+ color: #858585;
30
+ margin-bottom: 1.5rem;
31
+ text-align: center;
32
+ }
33
+ .auth-form {
34
+ display: flex;
35
+ flex-direction: column;
36
+ gap: 0.75rem;
37
+ }
38
+ .auth-input {
39
+ padding: 0.5rem 0.75rem;
40
+ font-size: 14px;
41
+ background: #3c3c3c;
42
+ border: 1px solid #555;
43
+ border-radius: 4px;
44
+ color: #cccccc;
45
+ outline: none;
46
+ }
47
+ .auth-input:focus {
48
+ border-color: #007acc;
49
+ }
50
+ .auth-input::placeholder {
51
+ color: #858585;
52
+ }
53
+ .auth-error {
54
+ color: #f48771;
55
+ font-size: 12px;
56
+ }
57
+ .auth-btn {
58
+ padding: 0.6rem 1rem;
59
+ font-size: 14px;
60
+ background: #0e639c;
61
+ color: #fff;
62
+ border: none;
63
+ border-radius: 4px;
64
+ cursor: pointer;
65
+ margin-top: 0.25rem;
66
+ }
67
+ .auth-btn:hover:not(:disabled) {
68
+ background: #1177bb;
69
+ }
70
+ .auth-btn:disabled {
71
+ opacity: 0.7;
72
+ cursor: not-allowed;
73
+ }
74
+ .auth-switch {
75
+ margin-top: 1.25rem;
76
+ text-align: center;
77
+ font-size: 13px;
78
+ color: #858585;
79
+ }
80
+ .auth-link {
81
+ background: none;
82
+ border: none;
83
+ color: #4fc1ff;
84
+ cursor: pointer;
85
+ padding: 0;
86
+ font-size: inherit;
87
+ text-decoration: underline;
88
+ }
89
+ .auth-link:hover {
90
+ color: #75c7ff;
91
+ }
92
+ .auth-close {
93
+ position: absolute;
94
+ top: 8px;
95
+ right: 8px;
96
+ background: none;
97
+ border: none;
98
+ color: #858585;
99
+ font-size: 1.5rem;
100
+ cursor: pointer;
101
+ line-height: 1;
102
+ padding: 4px;
103
+ }
104
+ .auth-close:hover {
105
+ color: #cccccc;
106
+ }
107
+
108
+ /* ─── Auth overlay (Sign in / Sign up modal) ─────────────────────────────── */
109
+ .auth-overlay {
110
+ position: fixed;
111
+ inset: 0;
112
+ z-index: 1000;
113
+ display: flex;
114
+ align-items: center;
115
+ justify-content: center;
116
+ padding: 1rem;
117
+ cursor: default;
118
+ background: transparent;
119
+ }
120
+ .auth-overlay-content {
121
+ position: relative;
122
+ z-index: 1;
123
+ width: 100%;
124
+ max-width: 360px;
125
+ }
126
+
127
+ /* ─── Chat landing page (ChatGPT-style) ─────────────────────────────────── */
128
+ .chat-page {
129
+ min-height: 100vh;
130
+ background: #0d0d0d;
131
+ display: flex;
132
+ flex-direction: column;
133
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
134
+ }
135
+ .chat-page-header {
136
+ display: flex;
137
+ align-items: center;
138
+ justify-content: space-between;
139
+ padding: 12px 20px;
140
+ }
141
+ .chat-page-brand {
142
+ font-size: 1rem;
143
+ font-weight: 600;
144
+ color: #ececec;
145
+ }
146
+ .chat-page-signin {
147
+ padding: 6px 14px;
148
+ font-size: 13px;
149
+ }
150
+ .chat-page-main {
151
+ flex: 1;
152
+ display: flex;
153
+ flex-direction: column;
154
+ align-items: center;
155
+ justify-content: center;
156
+ padding: 2rem 1rem 4rem;
157
+ }
158
+ .chat-page-title {
159
+ font-size: 1.75rem;
160
+ font-weight: 600;
161
+ color: #ececec;
162
+ margin-bottom: 2rem;
163
+ text-align: center;
164
+ }
165
+ .chat-page-form {
166
+ width: 100%;
167
+ max-width: 640px;
168
+ }
169
+ .chat-page-input-wrap {
170
+ display: flex;
171
+ align-items: center;
172
+ gap: 0;
173
+ background: #2f2f2f;
174
+ border: 1px solid #404040;
175
+ border-radius: 12px;
176
+ padding: 4px 4px 4px 12px;
177
+ transition: border-color 0.15s, box-shadow 0.15s;
178
+ }
179
+ .chat-page-input-wrap:focus-within {
180
+ border-color: #0e639c;
181
+ box-shadow: 0 0 0 1px #0e639c;
182
+ }
183
+ .chat-page-plus {
184
+ width: 36px;
185
+ height: 36px;
186
+ display: flex;
187
+ align-items: center;
188
+ justify-content: center;
189
+ background: transparent;
190
+ border: none;
191
+ border-radius: 8px;
192
+ color: #ececec;
193
+ font-size: 1.5rem;
194
+ line-height: 1;
195
+ cursor: pointer;
196
+ flex-shrink: 0;
197
+ }
198
+ .chat-page-plus:hover {
199
+ background: #404040;
200
+ color: #fff;
201
+ }
202
+ .chat-page-input {
203
+ flex: 1;
204
+ min-width: 0;
205
+ padding: 12px 14px;
206
+ background: transparent;
207
+ border: none;
208
+ color: #ececec;
209
+ font-size: 1rem;
210
+ outline: none;
211
+ }
212
+ .chat-page-mic {
213
+ width: 36px;
214
+ height: 36px;
215
+ display: flex;
216
+ align-items: center;
217
+ justify-content: center;
218
+ background: transparent;
219
+ border: none;
220
+ border-radius: 8px;
221
+ color: #ececec;
222
+ cursor: pointer;
223
+ flex-shrink: 0;
224
+ }
225
+ .chat-page-mic:hover {
226
+ background: #404040;
227
+ color: #fff;
228
+ }
229
+ .chat-page-mic--active {
230
+ background: #0e639c;
231
+ color: #fff;
232
+ }
233
+ .chat-page-input::placeholder {
234
+ color: #8e8e8e;
235
+ }
236
+ .chat-page-message {
237
+ margin-top: 0.75rem;
238
+ padding: 0 4px;
239
+ font-size: 13px;
240
+ color: #8e8e8e;
241
+ }
242
+ .chat-page-message--success {
243
+ color: #4ec9b0;
244
+ }
245
+ .chat-page-message--error {
246
+ color: #f48771;
247
+ }
248
+ .chat-page-message--info {
249
+ color: #4fc1ff;
250
+ }
251
+ .chat-page-suggestions {
252
+ display: flex;
253
+ flex-wrap: wrap;
254
+ gap: 8px;
255
+ justify-content: center;
256
+ margin-top: 2rem;
257
+ max-width: 640px;
258
+ }
259
+ .chat-page-suggestion {
260
+ padding: 10px 16px;
261
+ background: #2f2f2f;
262
+ border: 1px solid #404040;
263
+ border-radius: 20px;
264
+ color: #c5c5c5;
265
+ font-size: 13px;
266
+ cursor: pointer;
267
+ transition: background 0.15s, border-color 0.15s;
268
+ }
269
+ .chat-page-suggestion:hover {
270
+ background: #3c3c3c;
271
+ border-color: #505050;
272
+ color: #ececec;
273
+ }
274
+
275
+ /* ─── App header (explorer layout) ───────────────────────────────────────── */
276
+ .app-header {
277
+ position: absolute;
278
+ top: 0;
279
+ right: 0;
280
+ padding: 8px 12px;
281
+ z-index: 10;
282
+ }
283
+ .app-header .auth-btn {
284
+ padding: 4px 10px;
285
+ font-size: 12px;
286
+ }
287
+ .profile-wrap {
288
+ position: relative;
289
+ }
290
+ .profile-trigger {
291
+ display: flex;
292
+ align-items: center;
293
+ justify-content: center;
294
+ padding: 4px;
295
+ background: none;
296
+ border: none;
297
+ color: #cccccc;
298
+ cursor: pointer;
299
+ border-radius: 4px;
300
+ }
301
+ .profile-trigger:hover {
302
+ color: #ffffff;
303
+ background: #3c3c3c;
304
+ }
305
+ .profile-dropdown {
306
+ position: absolute;
307
+ top: 100%;
308
+ right: 0;
309
+ margin-top: 4px;
310
+ min-width: 160px;
311
+ padding: 8px 0;
312
+ background: #252526;
313
+ border: 1px solid #3c3c3c;
314
+ border-radius: 4px;
315
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
316
+ z-index: 100;
317
+ }
318
+ .profile-dropdown-name {
319
+ padding: 8px 12px;
320
+ font-size: 12px;
321
+ color: #cccccc;
322
+ border-bottom: 1px solid #3c3c3c;
323
+ }
324
+ .profile-dropdown-signout {
325
+ display: block;
326
+ width: 100%;
327
+ padding: 8px 12px;
328
+ font-size: 12px;
329
+ text-align: left;
330
+ background: none;
331
+ border: none;
332
+ color: #cccccc;
333
+ cursor: pointer;
334
+ }
335
+ .profile-dropdown-signout:hover {
336
+ background: #3c3c3c;
337
+ color: #fff;
338
+ }
339
+
340
+ /* ─── App Layout ────────────────────────────────────────────────────────── */
341
+ .app-container {
342
+ display: flex;
343
+ flex-direction: column;
344
+ height: 100vh;
345
+ width: 100vw;
346
+ background: #1e1e1e;
347
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", sans-serif;
348
+ font-size: 13px;
349
+ }
350
+ .app-main-row {
351
+ display: flex;
352
+ flex: 1;
353
+ min-height: 0;
354
+ align-items: stretch;
355
+ }
356
+
357
+ .pane-resizer--vertical {
358
+ width: 6px;
359
+ flex-shrink: 0;
360
+ cursor: col-resize;
361
+ touch-action: none;
362
+ user-select: none;
363
+ background: #3c3c3c;
364
+ align-self: stretch;
365
+ position: relative;
366
+ z-index: 5;
367
+ flex-grow: 0;
368
+ }
369
+ .pane-resizer--vertical:hover,
370
+ .pane-resizer--vertical.pane-resizer--active {
371
+ background: #007acc;
372
+ }
373
+ .query-folder-ref {
374
+ margin-top: 10px;
375
+ padding-top: 8px;
376
+ border-top: 1px solid #3c3c3c;
377
+ }
378
+ .query-folder-ref-title {
379
+ font-size: 10px;
380
+ font-weight: 700;
381
+ text-transform: uppercase;
382
+ color: #858585;
383
+ margin-bottom: 6px;
384
+ }
385
+ .query-folder-ref-body {
386
+ font-size: 11px;
387
+ color: #a0a0a0;
388
+ white-space: pre-wrap;
389
+ word-break: break-word;
390
+ max-height: 160px;
391
+ overflow: auto;
392
+ background: #1e1e1e;
393
+ padding: 8px;
394
+ border-radius: 4px;
395
+ }
396
+ .query-source-meta {
397
+ font-size: 10px;
398
+ color: #858585;
399
+ margin-bottom: 4px;
400
+ }
401
+ .study-panel {
402
+ border-top: 1px solid #3c3c3c;
403
+ padding: 10px 12px 16px;
404
+ flex: 1;
405
+ min-height: 200px;
406
+ display: flex;
407
+ flex-direction: column;
408
+ color: #ccc;
409
+ }
410
+ .study-context {
411
+ margin-bottom: 10px;
412
+ padding: 8px;
413
+ border: 1px solid #3c3c3c;
414
+ border-radius: 6px;
415
+ background: #252526;
416
+ font-size: 11px;
417
+ line-height: 1.35;
418
+ }
419
+ .study-context-line {
420
+ white-space: nowrap;
421
+ overflow: hidden;
422
+ text-overflow: ellipsis;
423
+ }
424
+ .study-tabs {
425
+ display: flex;
426
+ flex-wrap: wrap;
427
+ gap: 6px;
428
+ margin-bottom: 10px;
429
+ }
430
+ .study-tabs button {
431
+ background: #3c3c3c;
432
+ border: 1px solid #555;
433
+ color: #ccc;
434
+ padding: 4px 10px;
435
+ border-radius: 4px;
436
+ cursor: pointer;
437
+ font-size: 11px;
438
+ }
439
+ .study-tabs button.active {
440
+ background: #0e639c;
441
+ border-color: #1177bb;
442
+ color: #fff;
443
+ }
444
+ .study-action {
445
+ background: #0e639c;
446
+ border: none;
447
+ color: #fff;
448
+ padding: 6px 12px;
449
+ border-radius: 4px;
450
+ cursor: pointer;
451
+ font-size: 12px;
452
+ margin-bottom: 10px;
453
+ }
454
+ .study-action:disabled { opacity: 0.5; cursor: not-allowed; }
455
+ .study-error { color: #f48771; font-size: 12px; margin-bottom: 8px; }
456
+ .study-hint { font-size: 11px; color: #858585; margin-bottom: 8px; }
457
+ .flashcard { margin-top: 8px; }
458
+ .flashcard-index { font-size: 11px; color: #858585; margin-bottom: 6px; }
459
+ .flashcard-face {
460
+ width: 100%;
461
+ min-height: 100px;
462
+ text-align: left;
463
+ padding: 12px;
464
+ background: #2d2d30;
465
+ border: 1px solid #3c3c3c;
466
+ border-radius: 6px;
467
+ color: #ccc;
468
+ cursor: pointer;
469
+ font-size: 13px;
470
+ line-height: 1.45;
471
+ }
472
+ .flashcard-nav {
473
+ display: flex;
474
+ gap: 8px;
475
+ margin-top: 10px;
476
+ }
477
+ .flashcard-nav button {
478
+ background: #3c3c3c;
479
+ border: 1px solid #555;
480
+ color: #ccc;
481
+ padding: 4px 10px;
482
+ border-radius: 4px;
483
+ cursor: pointer;
484
+ }
485
+ .mcq-block { margin-top: 8px; }
486
+ .mcq-q { margin-bottom: 10px; line-height: 1.4; }
487
+ .mcq-options { list-style: none; margin-bottom: 8px; }
488
+ .mcq-options li { margin-bottom: 6px; }
489
+ .mcq-options button {
490
+ width: 100%;
491
+ text-align: left;
492
+ padding: 8px 10px;
493
+ background: #2d2d30;
494
+ border: 1px solid #3c3c3c;
495
+ color: #ccc;
496
+ border-radius: 4px;
497
+ cursor: pointer;
498
+ }
499
+ .mcq-options button.picked { border-color: #007acc; }
500
+ .mcq-ans { font-size: 12px; color: #89d185; }
501
+ .react-flow-wrap {
502
+ height: 320px;
503
+ border: 1px solid #3c3c3c;
504
+ border-radius: 6px;
505
+ margin-top: 8px;
506
+ }
507
+
508
+ /* ─── Left Sidebar ──────────────────────────────────────────────────────── */
509
+ .left-sidebar {
510
+ flex-shrink: 0;
511
+ flex-grow: 0;
512
+ min-width: 150px;
513
+ max-width: 480px;
514
+ border-right: none;
515
+ background-color: #252526;
516
+ display: flex;
517
+ flex-direction: column;
518
+ overflow: hidden;
519
+ }
520
+
521
+ /* ─── Right Sidebar ─────────────────────────────────────────────────────── */
522
+ .right-sidebar {
523
+ flex-shrink: 0;
524
+ flex-grow: 0;
525
+ min-width: 200px;
526
+ max-width: 520px;
527
+ border-left: none;
528
+ background-color: #252526;
529
+ display: flex;
530
+ flex-direction: column;
531
+ overflow: hidden;
532
+ }
533
+
534
+ /* ─── Preview Pane ──────────────────────────────────────────────────────── */
535
+ .preview-pane {
536
+ flex: 1;
537
+ background-color: #1e1e1e;
538
+ overflow: hidden;
539
+ display: flex;
540
+ flex-direction: column;
541
+ }
542
+ .preview-content {
543
+ flex: 1;
544
+ overflow: hidden;
545
+ display: flex;
546
+ justify-content: center;
547
+ align-items: center;
548
+ }
549
+ .preview-pane img,
550
+ .preview-pane embed,
551
+ .preview-pane iframe {
552
+ width: 100%;
553
+ height: 100%;
554
+ object-fit: contain;
555
+ display: block;
556
+ }
557
+ .preview-placeholder {
558
+ display: flex;
559
+ flex-direction: column;
560
+ justify-content: center;
561
+ align-items: center;
562
+ height: 100%;
563
+ color: #6e6e6e;
564
+ font-size: 13px;
565
+ gap: 12px;
566
+ }
567
+ .preview-placeholder-icon { font-size: 3rem; opacity: 0.5; }
568
+ .preview-placeholder p {
569
+ max-width: 320px;
570
+ text-align: center;
571
+ line-height: 1.45;
572
+ margin: 0;
573
+ }
574
+ .preview-attach-input {
575
+ position: absolute;
576
+ width: 0;
577
+ height: 0;
578
+ opacity: 0;
579
+ pointer-events: none;
580
+ }
581
+ .preview-attach-btn {
582
+ margin-top: 4px;
583
+ padding: 8px 16px;
584
+ font-size: 13px;
585
+ border-radius: 4px;
586
+ border: 1px solid #3c3c3c;
587
+ background: #2d2d2d;
588
+ color: #ccc;
589
+ cursor: pointer;
590
+ }
591
+ .preview-attach-btn:hover {
592
+ background: #3c3c3c;
593
+ color: #fff;
594
+ }
595
+
596
+ /* Local disk mirror (NoteScanner folder) */
597
+ .vsc2-disk-bar {
598
+ padding: 8px 10px;
599
+ font-size: 11px;
600
+ line-height: 1.35;
601
+ color: #9d9d9d;
602
+ border-bottom: 1px solid #2d2d2d;
603
+ background: #1f1f1f;
604
+ }
605
+ .vsc2-disk-bar-row {
606
+ display: flex;
607
+ flex-wrap: wrap;
608
+ align-items: center;
609
+ gap: 8px;
610
+ }
611
+ .vsc2-disk-bar-text {
612
+ flex: 1;
613
+ min-width: 140px;
614
+ }
615
+ .vsc2-disk-bar-text strong {
616
+ color: #c8c8c8;
617
+ font-weight: 600;
618
+ }
619
+ .vsc2-disk-bar-btn {
620
+ flex-shrink: 0;
621
+ padding: 4px 10px;
622
+ font-size: 11px;
623
+ border-radius: 3px;
624
+ border: 1px solid #3c3c3c;
625
+ background: #2d2d2d;
626
+ color: #ccc;
627
+ cursor: pointer;
628
+ }
629
+ .vsc2-disk-bar-btn:hover {
630
+ background: #3c3c3c;
631
+ color: #fff;
632
+ }
633
+
634
+ /* ─── Explorer (vsc2) ───────────────────────────────────────────────────── */
635
+ .vsc2-explorer {
636
+ display: flex;
637
+ flex-direction: column;
638
+ height: 100%;
639
+ overflow: hidden;
640
+ background: #252526;
641
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
642
+ font-size: 13px;
643
+ color: #cccccc;
644
+ user-select: none;
645
+ }
646
+
647
+ .vsc2-header {
648
+ display: flex;
649
+ align-items: center;
650
+ justify-content: space-between;
651
+ padding: 0 8px 0 12px;
652
+ height: 35px;
653
+ min-height: 35px;
654
+ flex-shrink: 0;
655
+ }
656
+ .vsc2-header-title {
657
+ font-size: 11px;
658
+ font-weight: 600;
659
+ letter-spacing: 0.02em;
660
+ color: #cccccc;
661
+ text-transform: none;
662
+ overflow: hidden;
663
+ text-overflow: ellipsis;
664
+ white-space: nowrap;
665
+ margin-right: 8px;
666
+ cursor: pointer;
667
+ border-radius: 3px;
668
+ padding: 2px 4px;
669
+ margin-left: -4px;
670
+ }
671
+ .vsc2-header-title:hover {
672
+ color: #fff;
673
+ background: #3c3c3c;
674
+ }
675
+ .vsc2-header-title:focus-visible {
676
+ outline: 1px solid #007acc;
677
+ outline-offset: 1px;
678
+ }
679
+
680
+ .vsc2-header-menu-wrap {
681
+ position: relative;
682
+ }
683
+ .vsc2-dropdown {
684
+ position: absolute;
685
+ top: 100%;
686
+ right: 0;
687
+ margin-top: 2px;
688
+ min-width: 168px;
689
+ padding: 4px 0;
690
+ background: #252526;
691
+ border: 1px solid #454545;
692
+ border-radius: 3px;
693
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.45);
694
+ z-index: 50;
695
+ }
696
+ .vsc2-dropdown-item {
697
+ display: block;
698
+ width: 100%;
699
+ padding: 6px 12px;
700
+ font-size: 12px;
701
+ text-align: left;
702
+ color: #cccccc;
703
+ background: none;
704
+ border: none;
705
+ cursor: pointer;
706
+ }
707
+ .vsc2-dropdown-item:hover {
708
+ background: #094771;
709
+ color: #fff;
710
+ }
711
+ .vsc2-header-actions {
712
+ display: flex;
713
+ align-items: center;
714
+ gap: 0;
715
+ flex-shrink: 0;
716
+ opacity: 1;
717
+ }
718
+ .vsc2-header-btn {
719
+ display: flex;
720
+ align-items: center;
721
+ justify-content: center;
722
+ width: 24px;
723
+ height: 24px;
724
+ border: none;
725
+ border-radius: 4px;
726
+ background: transparent;
727
+ color: #c5c5c5;
728
+ cursor: pointer;
729
+ }
730
+ .vsc2-header-btn:hover {
731
+ background: #3c3c3c;
732
+ color: #fff;
733
+ }
734
+
735
+ .vsc2-create-row {
736
+ display: flex;
737
+ align-items: center;
738
+ gap: 6px;
739
+ padding: 5px 8px;
740
+ border-bottom: 1px solid #3c3c3c;
741
+ flex-shrink: 0;
742
+ }
743
+ .vsc2-create-input {
744
+ flex: 1;
745
+ min-width: 0;
746
+ height: 22px;
747
+ padding: 0 6px;
748
+ font-size: 12px;
749
+ font-family: inherit;
750
+ color: #cccccc;
751
+ background: #3c3c3c;
752
+ border: 1px solid #007acc;
753
+ border-radius: 2px;
754
+ outline: none;
755
+ }
756
+ .vsc2-create-input::placeholder { color: #6e6e6e; }
757
+ .vsc2-create-btn {
758
+ flex-shrink: 0;
759
+ padding: 1px 8px;
760
+ height: 22px;
761
+ font-size: 11px;
762
+ background: #0e639c;
763
+ color: #fff;
764
+ border: none;
765
+ border-radius: 2px;
766
+ cursor: pointer;
767
+ }
768
+ .vsc2-create-btn:disabled { opacity: 0.5; cursor: not-allowed; }
769
+
770
+ .vsc2-tree {
771
+ flex: 1;
772
+ overflow-y: auto;
773
+ overflow-x: hidden;
774
+ padding-bottom: 8px;
775
+ }
776
+ .vsc2-tree::-webkit-scrollbar { width: 6px; }
777
+ .vsc2-tree::-webkit-scrollbar-track { background: transparent; }
778
+ .vsc2-tree::-webkit-scrollbar-thumb { background: #424242; border-radius: 3px; }
779
+ .vsc2-tree::-webkit-scrollbar-thumb:hover { background: #686868; }
780
+
781
+ .vsc2-empty {
782
+ padding: 12px 12px;
783
+ font-size: 12px;
784
+ color: #6e6e6e;
785
+ line-height: 1.5;
786
+ }
787
+ .vsc2-node { position: relative; }
788
+ .vsc2-children { position: relative; }
789
+
790
+ .vsc2-row {
791
+ position: relative;
792
+ display: flex;
793
+ align-items: center;
794
+ height: 22px;
795
+ cursor: pointer;
796
+ color: #cccccc;
797
+ padding-right: 6px;
798
+ white-space: nowrap;
799
+ overflow: hidden;
800
+ }
801
+ .vsc2-row:hover { background: #2a2d2e; }
802
+ .vsc2-row--selected { background: #094771 !important; color: #fff; }
803
+ .vsc2-row--selected:hover { background: #0e639c !important; }
804
+ .vsc2-row--drop {
805
+ background: #04395e !important;
806
+ outline: 1px dashed #007acc;
807
+ outline-offset: -1px;
808
+ }
809
+
810
+ .vsc2-indent-guide {
811
+ position: absolute;
812
+ top: 0;
813
+ bottom: 0;
814
+ width: 1px;
815
+ background: #404040;
816
+ pointer-events: none;
817
+ }
818
+ .vsc2-row:hover .vsc2-indent-guide { background: #555; }
819
+ .vsc2-row--selected .vsc2-indent-guide { background: rgba(255,255,255,0.15); }
820
+
821
+ .vsc2-chevron {
822
+ display: flex;
823
+ align-items: center;
824
+ justify-content: center;
825
+ width: 16px;
826
+ min-width: 16px;
827
+ height: 22px;
828
+ color: #c5c5c5;
829
+ transition: transform 0.12s ease;
830
+ flex-shrink: 0;
831
+ position: relative;
832
+ z-index: 1;
833
+ }
834
+ .vsc2-chevron--open { transform: rotate(90deg); }
835
+
836
+ .vsc2-folder-icon {
837
+ display: flex;
838
+ align-items: center;
839
+ width: 16px;
840
+ min-width: 16px;
841
+ height: 16px;
842
+ margin-right: 6px;
843
+ color: #c09553;
844
+ flex-shrink: 0;
845
+ position: relative;
846
+ z-index: 1;
847
+ }
848
+ .vsc2-folder-icon--open { color: #dcb67a; }
849
+
850
+ .vsc2-file-icon {
851
+ display: flex;
852
+ align-items: center;
853
+ width: 16px;
854
+ min-width: 16px;
855
+ height: 16px;
856
+ margin-right: 6px;
857
+ flex-shrink: 0;
858
+ position: relative;
859
+ z-index: 1;
860
+ }
861
+ .vsc2-icon-pdf { color: #f14c4c; }
862
+ .vsc2-icon-image { color: #6a9955; }
863
+ .vsc2-icon-text { color: #9cdcfe; }
864
+ .vsc2-icon-default { color: #c5c5c5; }
865
+ .vsc2-row--selected .vsc2-file-icon,
866
+ .vsc2-row--selected .vsc2-folder-icon { color: #fff !important; }
867
+
868
+ .vsc2-row-name-hit {
869
+ display: flex;
870
+ align-items: center;
871
+ flex: 1;
872
+ min-width: 0;
873
+ overflow: hidden;
874
+ }
875
+
876
+ .vsc2-label {
877
+ flex: 1;
878
+ min-width: 0;
879
+ overflow: hidden;
880
+ text-overflow: ellipsis;
881
+ font-size: 13px;
882
+ line-height: 22px;
883
+ position: relative;
884
+ z-index: 1;
885
+ }
886
+
887
+ .vsc2-context-menu {
888
+ position: fixed;
889
+ z-index: 10000;
890
+ min-width: 168px;
891
+ padding: 4px 0;
892
+ background: #252526;
893
+ border: 1px solid #454545;
894
+ box-shadow: 0 4px 14px rgba(0, 0, 0, 0.45);
895
+ border-radius: 3px;
896
+ }
897
+ .vsc2-context-menu-item {
898
+ display: block;
899
+ width: 100%;
900
+ text-align: left;
901
+ padding: 6px 14px;
902
+ border: none;
903
+ background: transparent;
904
+ color: #cccccc;
905
+ font-size: 13px;
906
+ cursor: pointer;
907
+ font-family: inherit;
908
+ }
909
+ .vsc2-context-menu-item:hover {
910
+ background: #094771;
911
+ color: #fff;
912
+ }
913
+ .vsc2-context-menu-item--danger:hover {
914
+ background: #5a1d1d;
915
+ color: #f48771;
916
+ }
917
+
918
+ .vsc2-root-drop {
919
+ display: flex;
920
+ align-items: center;
921
+ height: 22px;
922
+ padding: 0 12px;
923
+ font-size: 12px;
924
+ color: #6e6e6e;
925
+ font-style: italic;
926
+ cursor: default;
927
+ }
928
+ .vsc2-root-drop.vsc2-row--drop { color: #ccc; font-style: normal; }
929
+
930
+ /* ─── Right Sidebar Content ─────────────────────────────────────────────── */
931
+ .right-sidebar-content {
932
+ flex: 1;
933
+ overflow-y: auto;
934
+ background: #252526;
935
+ padding-top: 48px;
936
+ display: flex;
937
+ flex-direction: column;
938
+ min-height: 0;
939
+ }
940
+ .right-sidebar-content::-webkit-scrollbar { width: 6px; }
941
+ .right-sidebar-content::-webkit-scrollbar-track { background: transparent; }
942
+ .right-sidebar-content::-webkit-scrollbar-thumb { background: #424242; border-radius: 3px; }
943
+
944
+ /* ─── Query Interface ───────────────────────────────────────────────────── */
945
+ .query-interface {
946
+ padding: 12px;
947
+ background: #252526;
948
+ flex: 1;
949
+ min-height: 0;
950
+ max-height: 52vh;
951
+ display: flex;
952
+ flex-direction: column;
953
+ color: #cccccc;
954
+ }
955
+ .query-form-label-sr {
956
+ position: absolute;
957
+ width: 1px;
958
+ height: 1px;
959
+ padding: 0;
960
+ margin: -1px;
961
+ overflow: hidden;
962
+ clip: rect(0, 0, 0, 0);
963
+ border: 0;
964
+ }
965
+ .query-form-bottom {
966
+ margin-top: auto;
967
+ padding-top: 12px;
968
+ flex-shrink: 0;
969
+ }
970
+ .query-input-wrap {
971
+ display: flex;
972
+ align-items: flex-end;
973
+ gap: 0;
974
+ background: #3c3c3c;
975
+ border: 1px solid #3c3c3c;
976
+ border-radius: 6px;
977
+ padding: 6px 6px 6px 10px;
978
+ }
979
+ .query-input-wrap:focus-within {
980
+ border-color: #007acc;
981
+ box-shadow: 0 0 0 1px #007acc;
982
+ }
983
+ .query-form-textarea-inline {
984
+ flex: 1;
985
+ min-height: 36px;
986
+ max-height: 120px;
987
+ padding: 6px 0;
988
+ margin: 0;
989
+ border: none;
990
+ background: transparent;
991
+ resize: none;
992
+ font-size: 13px;
993
+ color: #cccccc;
994
+ }
995
+ .query-form-textarea-inline::placeholder {
996
+ color: #858585;
997
+ }
998
+ .query-form-textarea-inline:focus {
999
+ outline: none;
1000
+ box-shadow: none;
1001
+ }
1002
+ .query-submit-icon {
1003
+ display: flex;
1004
+ align-items: center;
1005
+ justify-content: center;
1006
+ width: 36px;
1007
+ height: 36px;
1008
+ padding: 0;
1009
+ background: #0e639c;
1010
+ border: none;
1011
+ border-radius: 4px;
1012
+ color: #fff;
1013
+ cursor: pointer;
1014
+ flex-shrink: 0;
1015
+ }
1016
+ .query-input-icon {
1017
+ display: flex;
1018
+ align-items: center;
1019
+ justify-content: center;
1020
+ width: 32px;
1021
+ height: 32px;
1022
+ border: none;
1023
+ border-radius: 6px;
1024
+ background: transparent;
1025
+ color: #c5c5c5;
1026
+ cursor: pointer;
1027
+ flex-shrink: 0;
1028
+ }
1029
+ .query-input-icon:hover:not(:disabled) {
1030
+ background: #4a4a4a;
1031
+ color: #fff;
1032
+ }
1033
+ .query-input-icon:disabled {
1034
+ opacity: 0.6;
1035
+ cursor: not-allowed;
1036
+ }
1037
+ .query-input-icon--active {
1038
+ background: #0e639c;
1039
+ color: #fff;
1040
+ }
1041
+ .query-submit-icon:hover:not(:disabled) {
1042
+ background: #1177bb;
1043
+ }
1044
+ .query-submit-icon:disabled {
1045
+ background: #555;
1046
+ cursor: not-allowed;
1047
+ opacity: 0.8;
1048
+ }
1049
+ /* ─── Chat messages (user / assistant) ──────────────────────────────────── */
1050
+ .query-messages {
1051
+ flex: 1;
1052
+ overflow-y: auto;
1053
+ min-height: 0;
1054
+ display: flex;
1055
+ flex-direction: column;
1056
+ gap: 12px;
1057
+ padding-bottom: 8px;
1058
+ }
1059
+ .query-messages-empty {
1060
+ color: #6e6e6e;
1061
+ font-size: 12px;
1062
+ padding: 12px 0;
1063
+ text-align: center;
1064
+ }
1065
+ .query-message {
1066
+ display: flex;
1067
+ width: 100%;
1068
+ }
1069
+ .query-message--user {
1070
+ justify-content: flex-end;
1071
+ }
1072
+ .query-message--assistant {
1073
+ justify-content: flex-start;
1074
+ }
1075
+ .query-message-bubble {
1076
+ max-width: 95%;
1077
+ padding: 10px 12px;
1078
+ border-radius: 8px;
1079
+ font-size: 13px;
1080
+ line-height: 1.5;
1081
+ }
1082
+ .query-message--user .query-message-bubble {
1083
+ background: #0e639c;
1084
+ color: #fff;
1085
+ border-bottom-right-radius: 2px;
1086
+ }
1087
+ .query-message--assistant .query-message-bubble {
1088
+ background: #2d2d30;
1089
+ border: 1px solid #3c3c3c;
1090
+ color: #cccccc;
1091
+ border-bottom-left-radius: 2px;
1092
+ }
1093
+ .query-message-loading .query-message-content {
1094
+ color: #858585;
1095
+ font-style: italic;
1096
+ }
1097
+ .query-message-content {
1098
+ white-space: pre-wrap;
1099
+ word-break: break-word;
1100
+ }
1101
+ .query-message-bubble .query-sources {
1102
+ margin-top: 10px;
1103
+ padding-top: 8px;
1104
+ border-top: 1px solid #3c3c3c;
1105
+ }
1106
+ .query-message-bubble .query-sources-title {
1107
+ font-size: 10px;
1108
+ font-weight: 700;
1109
+ text-transform: uppercase;
1110
+ color: #bbbcbd;
1111
+ margin-bottom: 6px;
1112
+ }
1113
+ .query-message-bubble .query-source-item {
1114
+ margin-bottom: 4px;
1115
+ padding: 6px;
1116
+ background: #3c3c3c;
1117
+ border-radius: 3px;
1118
+ font-size: 11px;
1119
+ color: #cccccc;
1120
+ border-left: 3px solid #007acc;
1121
+ }
1122
+
1123
+ /* ─── Responsive ────────────────────────────────────────────────────────── */
1124
+ @media (max-width: 768px) {
1125
+ .app-container { flex-direction: column; }
1126
+ .pane-resizer--vertical { display: none; }
1127
+ .left-sidebar, .right-sidebar {
1128
+ width: 100% !important;
1129
+ height: 25%;
1130
+ max-width: unset;
1131
+ border-right: 1px solid #3c3c3c;
1132
+ border-left: 1px solid #3c3c3c;
1133
+ }
1134
+ .preview-pane { width: 100%; height: 50%; }
1135
+ }
frontend/my-app/src/localDiskFolder.js ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Mirror the virtual tree into storage on the device.
3
+ *
4
+ * Primary (Chrome / Edge): user creates a folder named NoteScanner on disk, then selects it in the
5
+ * picker so the browser grants read/write access. The handle is stored in IndexedDB.
6
+ *
7
+ * Fallback: when showDirectoryPicker is unavailable, use OPFS (private browser storage).
8
+ */
9
+
10
+ import { sanitizeVirtualPath } from "./virtualPath";
11
+ import { registerLocalFile, getBlobUrlForPath } from "./localFileStore";
12
+
13
+ /** Bump this string to wipe all prior folder handles + linked flags (one-time migration on load). */
14
+ const MIRROR_STORAGE_VERSION = "v20260407-reset";
15
+ const SCHEMA_KEY = "notescanner-mirror-schema";
16
+ const LEGACY_IDB_NAMES = ["notescanner-fs-handles"];
17
+
18
+ const IDB_NAME = `notescanner-fs-handles-${MIRROR_STORAGE_VERSION}`;
19
+ const IDB_STORE = "handles";
20
+ const IDB_KEY = "notesRoot";
21
+
22
+ /** Sync mirror of “we saved a directory handle” so UI can call showDirectoryPicker without awaiting IDB first (preserves user activation). */
23
+ const LS_DISK_ROOT_LINKED = `notescanner-root-linked-${MIRROR_STORAGE_VERSION}`;
24
+
25
+ /**
26
+ * Delete old IndexedDB + localStorage from previous NoteScanner builds so folder linking starts clean.
27
+ */
28
+ function migrateMirrorStorage() {
29
+ if (typeof window === "undefined" || typeof indexedDB === "undefined") return;
30
+ try {
31
+ if (typeof localStorage === "undefined") return;
32
+ const applied = localStorage.getItem(SCHEMA_KEY);
33
+ if (applied === MIRROR_STORAGE_VERSION) return;
34
+
35
+ const toDelete = new Set(LEGACY_IDB_NAMES);
36
+ if (applied) {
37
+ toDelete.add(`notescanner-fs-handles-${applied}`);
38
+ }
39
+ for (const name of toDelete) {
40
+ try {
41
+ indexedDB.deleteDatabase(name);
42
+ } catch {
43
+ /* ignore */
44
+ }
45
+ }
46
+ if (applied) {
47
+ try {
48
+ localStorage.removeItem(`notescanner-root-linked-${applied}`);
49
+ } catch {
50
+ /* ignore */
51
+ }
52
+ }
53
+ try {
54
+ localStorage.removeItem("notescanner-notes-root-linked");
55
+ } catch {
56
+ /* ignore */
57
+ }
58
+ localStorage.setItem(SCHEMA_KEY, MIRROR_STORAGE_VERSION);
59
+ } catch {
60
+ /* ignore */
61
+ }
62
+ }
63
+
64
+ migrateMirrorStorage();
65
+
66
+ function setDiskRootLinkedFlag(on) {
67
+ try {
68
+ if (typeof localStorage === "undefined") return;
69
+ if (on) localStorage.setItem(LS_DISK_ROOT_LINKED, "1");
70
+ else localStorage.removeItem(LS_DISK_ROOT_LINKED);
71
+ } catch {
72
+ /* private mode */
73
+ }
74
+ }
75
+
76
+ /** Synchronous; use before showDirectoryPicker so no prior await breaks the user gesture. */
77
+ export function hasUserDiskRootLinkedSync() {
78
+ try {
79
+ return typeof localStorage !== "undefined" && localStorage.getItem(LS_DISK_ROOT_LINKED) === "1";
80
+ } catch {
81
+ return false;
82
+ }
83
+ }
84
+
85
+ /** Shown in UI; directory name under OPFS or inside the user-picked parent. */
86
+ export const RECOMMENDED_ROOT_FOLDER_NAME = "NoteScanner";
87
+
88
+ function normRel(p) {
89
+ return (p || "").replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
90
+ }
91
+
92
+ /** OPFS: no picker; create NoteScanner under the origin root. */
93
+ export function isOpfsMirrorSupported() {
94
+ return typeof navigator !== "undefined" && typeof navigator.storage?.getDirectory === "function";
95
+ }
96
+
97
+ /** Optional visible folder on disk (Chrome, Edge, …). */
98
+ export function isUserFolderPickerSupported() {
99
+ return typeof window !== "undefined" && typeof window.showDirectoryPicker === "function";
100
+ }
101
+
102
+ /** Any local mirroring (OPFS and/or picker). */
103
+ export function isLocalDiskMirrorSupported() {
104
+ return isOpfsMirrorSupported() || isUserFolderPickerSupported();
105
+ }
106
+
107
+ function openDb() {
108
+ return new Promise((resolve, reject) => {
109
+ const req = indexedDB.open(IDB_NAME, 1);
110
+ req.onupgradeneeded = () => {
111
+ if (!req.result.objectStoreNames.contains(IDB_STORE)) {
112
+ req.result.createObjectStore(IDB_STORE);
113
+ }
114
+ };
115
+ req.onsuccess = () => resolve(req.result);
116
+ req.onerror = () => reject(req.error);
117
+ });
118
+ }
119
+
120
+ export async function loadStoredRootHandle() {
121
+ try {
122
+ const db = await openDb();
123
+ return new Promise((resolve, reject) => {
124
+ const tx = db.transaction(IDB_STORE, "readonly");
125
+ const r = tx.objectStore(IDB_STORE).get(IDB_KEY);
126
+ r.onsuccess = () => {
127
+ const val = r.result ?? null;
128
+ if (val) setDiskRootLinkedFlag(true);
129
+ resolve(val);
130
+ };
131
+ r.onerror = () => reject(r.error);
132
+ });
133
+ } catch {
134
+ return null;
135
+ }
136
+ }
137
+
138
+ export async function saveRootHandle(handle) {
139
+ const db = await openDb();
140
+ return new Promise((resolve, reject) => {
141
+ const tx = db.transaction(IDB_STORE, "readwrite");
142
+ tx.objectStore(IDB_STORE).put(handle, IDB_KEY);
143
+ tx.oncomplete = () => {
144
+ setDiskRootLinkedFlag(true);
145
+ resolve();
146
+ };
147
+ tx.onerror = () => reject(tx.error);
148
+ });
149
+ }
150
+
151
+ export async function clearStoredRootHandle() {
152
+ const db = await openDb();
153
+ return new Promise((resolve, reject) => {
154
+ const tx = db.transaction(IDB_STORE, "readwrite");
155
+ tx.objectStore(IDB_STORE).delete(IDB_KEY);
156
+ tx.oncomplete = () => {
157
+ setDiskRootLinkedFlag(false);
158
+ resolve();
159
+ };
160
+ tx.onerror = () => reject(tx.error);
161
+ });
162
+ }
163
+
164
+ /**
165
+ * Ask the browser for persistent storage (reduces eviction). No folder picker.
166
+ * May show a permission prompt depending on browser and policy.
167
+ */
168
+ export async function ensurePersistentStoragePermission() {
169
+ if (!navigator.storage?.persist) return false;
170
+ try {
171
+ return await navigator.storage.persist();
172
+ } catch {
173
+ return false;
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Ask for read/write on a user-picked directory handle (call from a gesture when possible).
179
+ */
180
+ export async function requestRootPermission(handle) {
181
+ if (!handle?.queryPermission) return "granted";
182
+ let state = await handle.queryPermission({ mode: "readwrite" });
183
+ if (state === "prompt" && handle.requestPermission) {
184
+ state = await handle.requestPermission({ mode: "readwrite" });
185
+ }
186
+ return state;
187
+ }
188
+
189
+ async function getOpfsNoteScannerRoot() {
190
+ await ensurePersistentStoragePermission();
191
+ const opfs = await navigator.storage.getDirectory();
192
+ return opfs.getDirectoryHandle(RECOMMENDED_ROOT_FOLDER_NAME, { create: true });
193
+ }
194
+
195
+ /**
196
+ * Resolve the directory used for mirroring: linked user folder if permitted; else OPFS only when
197
+ * the directory picker API is not available (otherwise callers must link or pick on first folder).
198
+ */
199
+ export async function getNotesMirrorRoot() {
200
+ const h = await loadStoredRootHandle();
201
+ if (h) {
202
+ const perm = await requestRootPermission(h);
203
+ if (perm === "granted") {
204
+ return { root: h, source: "user_folder" };
205
+ }
206
+ }
207
+ if (!isUserFolderPickerSupported() && isOpfsMirrorSupported()) {
208
+ try {
209
+ const root = await getOpfsNoteScannerRoot();
210
+ return { root, source: "opfs" };
211
+ } catch {
212
+ return { root: null, source: "none" };
213
+ }
214
+ }
215
+ return { root: null, source: "none" };
216
+ }
217
+
218
+ /**
219
+ * Guide the user to create a NoteScanner folder on disk, then pick that folder for read/write access.
220
+ * @returns {Promise<FileSystemDirectoryHandle|null>} null if the user cancels or skips
221
+ */
222
+ export async function linkNoteScannerFolder() {
223
+ if (!isUserFolderPickerSupported()) {
224
+ throw new Error(
225
+ "This browser cannot pick a folder on disk. Local copies use private browser storage instead.",
226
+ );
227
+ }
228
+ const ok = window.confirm(
229
+ `Set up local files on your computer:\n\n` +
230
+ `1. In Finder / File Explorer, create a new folder named "${RECOMMENDED_ROOT_FOLDER_NAME}" wherever you want (e.g. Documents or Desktop).\n\n` +
231
+ `2. Click OK here, then in the next dialog select that "${RECOMMENDED_ROOT_FOLDER_NAME}" folder and allow access so NoteScanner can save your courses there.`,
232
+ );
233
+ if (!ok) return null;
234
+
235
+ let handle;
236
+ try {
237
+ handle = await window.showDirectoryPicker({
238
+ mode: "readwrite",
239
+ // Browser limit: id must be ≤ 32 characters (Chromium).
240
+ id: "notescanner-notes-root-pick",
241
+ });
242
+ } catch (e) {
243
+ if (e?.name === "AbortError") return null;
244
+ throw e;
245
+ }
246
+
247
+ if (handle.name !== RECOMMENDED_ROOT_FOLDER_NAME) {
248
+ const proceed = window.confirm(
249
+ `You selected “${handle.name}”. It should be named “${RECOMMENDED_ROOT_FOLDER_NAME}” so paths stay clear. Continue with this folder anyway?`,
250
+ );
251
+ if (!proceed) return null;
252
+ }
253
+
254
+ const perm = await requestRootPermission(handle);
255
+ if (perm !== "granted") {
256
+ throw new Error(
257
+ "Read/write access to this folder was denied. Grant access so NoteScanner can save files there.",
258
+ );
259
+ }
260
+ await saveRootHandle(handle);
261
+ return handle;
262
+ }
263
+
264
+ export async function unlinkNoteScannerFolder() {
265
+ await clearStoredRootHandle();
266
+ }
267
+
268
+ /**
269
+ * Wipe folder-link storage (IndexedDB + flags). Use after a bad link or to redo first-folder setup.
270
+ * Optional: `location.reload()` afterward so all tabs pick up a clean state.
271
+ */
272
+ export async function flushLocalDiskMirrorData() {
273
+ try {
274
+ await new Promise((resolve) => {
275
+ const req = indexedDB.deleteDatabase(IDB_NAME);
276
+ req.onsuccess = req.onerror = req.onblocked = () => resolve();
277
+ });
278
+ } catch {
279
+ /* ignore */
280
+ }
281
+ try {
282
+ localStorage.removeItem(LS_DISK_ROOT_LINKED);
283
+ localStorage.removeItem(SCHEMA_KEY);
284
+ localStorage.removeItem("notescanner-notes-root-linked");
285
+ } catch {
286
+ /* ignore */
287
+ }
288
+ }
289
+
290
+ async function walkDir(root, pathParts, create) {
291
+ let dir = root;
292
+ for (const part of pathParts) {
293
+ if (!part) continue;
294
+ dir = await dir.getDirectoryHandle(part, { create: !!create });
295
+ }
296
+ return dir;
297
+ }
298
+
299
+ /** Ensure directory chain exists for rel path (directories only, no file name). */
300
+ export async function mirrorEnsureDir(root, relDirPath) {
301
+ const parts = sanitizeVirtualPath(normRel(relDirPath)).split("/").filter(Boolean);
302
+ if (parts.length === 0) return root;
303
+ return walkDir(root, parts, true);
304
+ }
305
+
306
+ export async function mirrorWriteFile(root, relPath, blobOrFile) {
307
+ const n = sanitizeVirtualPath(normRel(relPath));
308
+ if (!n) return;
309
+ const parts = n.split("/");
310
+ const name = parts.pop();
311
+ const parent = await walkDir(root, parts, true);
312
+ const fh = await parent.getFileHandle(name, { create: true });
313
+ const w = await fh.createWritable();
314
+ await w.write(blobOrFile);
315
+ await w.close();
316
+ }
317
+
318
+ export async function mirrorRemove(root, relPath, isFolder) {
319
+ const n = sanitizeVirtualPath(normRel(relPath));
320
+ if (!n) return;
321
+ const parts = n.split("/");
322
+ const leaf = parts.pop();
323
+ const parent = parts.length ? await walkDir(root, parts, false) : root;
324
+ if (!parent) return;
325
+ try {
326
+ await parent.removeEntry(leaf, { recursive: !!isFolder });
327
+ } catch {
328
+ /* missing on disk is fine */
329
+ }
330
+ }
331
+
332
+ async function getParentDir(root, relPath) {
333
+ const parts = normRel(relPath).split("/").filter(Boolean);
334
+ const leaf = parts.pop();
335
+ const parent = parts.length ? await walkDir(root, parts, false) : root;
336
+ return { parent, leaf };
337
+ }
338
+
339
+ export async function mirrorMoveFile(root, fromRel, toRel) {
340
+ const from = sanitizeVirtualPath(normRel(fromRel));
341
+ const to = sanitizeVirtualPath(normRel(toRel));
342
+ if (!from || !to) return;
343
+ const fromPn = await getParentDir(root, from);
344
+ const toParentParts = normRel(to).split("/").filter(Boolean);
345
+ const toName = toParentParts.pop();
346
+ await walkDir(root, toParentParts, true);
347
+ const toParent = toParentParts.length ? await walkDir(root, toParentParts, false) : root;
348
+ try {
349
+ const fh = await fromPn.parent.getFileHandle(fromPn.leaf);
350
+ if (typeof fh.move === "function") {
351
+ await fh.move(toParent, toName);
352
+ return;
353
+ }
354
+ } catch {
355
+ /* fall through */
356
+ }
357
+ try {
358
+ const fh = await fromPn.parent.getFileHandle(fromPn.leaf);
359
+ const file = await fh.getFile();
360
+ await mirrorWriteFile(root, to, file);
361
+ await fromPn.parent.removeEntry(fromPn.leaf);
362
+ } catch {
363
+ /* ignore */
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Best-effort folder rename/move on disk (Chrome supports directory move in newer versions).
369
+ */
370
+ export async function mirrorMoveFolder(root, fromRel, toRel) {
371
+ const from = sanitizeVirtualPath(normRel(fromRel));
372
+ const to = sanitizeVirtualPath(normRel(toRel));
373
+ if (!from || !to) return;
374
+ const fromPn = await getParentDir(root, from);
375
+ const toParts = normRel(to).split("/").filter(Boolean);
376
+ const newName = toParts.pop();
377
+ await walkDir(root, toParts, true);
378
+ const destParent = toParts.length ? await walkDir(root, toParts, false) : root;
379
+ try {
380
+ const dh = await fromPn.parent.getDirectoryHandle(fromPn.leaf);
381
+ if (typeof dh.move === "function") {
382
+ await dh.move(destParent, newName);
383
+ return;
384
+ }
385
+ } catch {
386
+ /* ignore */
387
+ }
388
+ }
389
+
390
+ /**
391
+ * Run fn(root) with the active mirror root (user-linked folder or OPFS), if any.
392
+ */
393
+ export async function withNotesRoot(fn) {
394
+ const { root } = await getNotesMirrorRoot();
395
+ if (root) await fn(root);
396
+ }
397
+
398
+ /**
399
+ * Write an uploaded file to the linked disk folder (or OPFS). Call {@link getNotesMirrorRoot}
400
+ * once at the start of the file input handler (before long network awaits) so permission can
401
+ * still be obtained while the user gesture is fresh.
402
+ *
403
+ * @param {File|Blob} file
404
+ * @param {string} relPath virtual path from the server (e.g. CS/paper.pdf)
405
+ * @param {FileSystemDirectoryHandle | null} [prefetchedRoot] from an earlier getNotesMirrorRoot()
406
+ */
407
+ export async function mirrorUploadedBytes(file, relPath, prefetchedRoot = null) {
408
+ const n = sanitizeVirtualPath(normRel(relPath));
409
+ if (!n || !file) return;
410
+ let root = prefetchedRoot;
411
+ if (!root) {
412
+ const got = await getNotesMirrorRoot();
413
+ root = got.root;
414
+ }
415
+ if (!root) return;
416
+ await mirrorWriteFile(root, n, file);
417
+ }
418
+
419
+ /**
420
+ * Read a file from the linked NoteScanner folder (or OPFS mirror) and register it for in-app preview.
421
+ * @param {string} relPath virtual path (e.g. CS/paper.pdf)
422
+ * @param {FileSystemDirectoryHandle | null} [prefetchedRoot]
423
+ * @returns {Promise<string|null>} blob URL, or null if missing / unreadable
424
+ */
425
+ export async function hydrateLocalPreviewFromMirror(relPath, prefetchedRoot = null) {
426
+ const n = sanitizeVirtualPath(normRel(relPath));
427
+ if (!n) return null;
428
+ let root = prefetchedRoot;
429
+ if (!root) {
430
+ const got = await getNotesMirrorRoot();
431
+ root = got.root;
432
+ }
433
+ if (!root) return null;
434
+ const parts = n.split("/").filter(Boolean);
435
+ const name = parts.pop();
436
+ if (!name) return null;
437
+ try {
438
+ const parent = await walkDir(root, parts, false);
439
+ const fh = await parent.getFileHandle(name);
440
+ const file = await fh.getFile();
441
+ registerLocalFile(n, file);
442
+ return getBlobUrlForPath(n);
443
+ } catch {
444
+ return null;
445
+ }
446
+ }
frontend/my-app/src/localFileStore.js ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Maps virtual note paths (same strings as the server tree) to blob URLs for in-app preview.
3
+ * Original PDFs/images stay on the device; nothing is fetched from the API as binaries.
4
+ */
5
+
6
+ import { sanitizeVirtualPath } from "./virtualPath";
7
+
8
+ const _map = new Map();
9
+
10
+ function _norm(p) {
11
+ return (p || "").replace(/\\/g, "/").replace(/^\/+/, "").replace(/\/+$/, "");
12
+ }
13
+
14
+ export function registerLocalFile(relPath, file) {
15
+ const key = sanitizeVirtualPath(_norm(relPath));
16
+ if (!key || !file) return;
17
+ const prev = _map.get(key);
18
+ if (prev?.url) URL.revokeObjectURL(prev.url);
19
+ _map.set(key, { url: URL.createObjectURL(file), file });
20
+ }
21
+
22
+ export function getBlobUrlForPath(relPath) {
23
+ const key = sanitizeVirtualPath(_norm(relPath));
24
+ return _map.get(key)?.url ?? null;
25
+ }
26
+
27
+ export function forgetPath(relPath) {
28
+ const key = sanitizeVirtualPath(_norm(relPath));
29
+ const prev = _map.get(key);
30
+ if (prev?.url) URL.revokeObjectURL(prev.url);
31
+ _map.delete(key);
32
+ }
33
+
34
+ export function forgetPathPrefix(folderPrefix) {
35
+ const prefix = sanitizeVirtualPath(_norm(folderPrefix));
36
+ if (!prefix) return;
37
+ const pfx = `${prefix}/`;
38
+ for (const k of [..._map.keys()]) {
39
+ if (k === prefix || k.startsWith(pfx)) forgetPath(k);
40
+ }
41
+ }
42
+
43
+ /**
44
+ * After a successful /move_path: re-key stored blobs from oldPath to newPath (file or whole folder).
45
+ */
46
+ export function relocateLocalEntry(oldPath, newPath, isFolder) {
47
+ const o = sanitizeVirtualPath(_norm(oldPath));
48
+ const n = sanitizeVirtualPath(_norm(newPath));
49
+ if (!o || !n) return;
50
+ if (!isFolder) {
51
+ const entry = _map.get(o);
52
+ if (!entry) return;
53
+ _map.delete(o);
54
+ const prev = _map.get(n);
55
+ if (prev?.url) URL.revokeObjectURL(prev.url);
56
+ _map.set(n, entry);
57
+ return;
58
+ }
59
+ const op = `${o}/`;
60
+ const pairs = [];
61
+ for (const k of _map.keys()) {
62
+ if (k === o) pairs.push([k, n]);
63
+ else if (k.startsWith(op)) pairs.push([k, `${n}/${k.slice(op.length)}`]);
64
+ }
65
+ pairs.sort((a, b) => b[0].length - a[0].length);
66
+ for (const [from, to] of pairs) {
67
+ const entry = _map.get(from);
68
+ if (!entry) continue;
69
+ _map.delete(from);
70
+ const prev = _map.get(to);
71
+ if (prev?.url) URL.revokeObjectURL(prev.url);
72
+ _map.set(to, entry);
73
+ }
74
+ }
frontend/my-app/src/main.jsx ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import { StrictMode } from 'react'
2
+ import { createRoot } from 'react-dom/client'
3
+ import './index.css'
4
+ import App from './App.jsx'
5
+
6
+ createRoot(document.getElementById('root')).render(
7
+ <StrictMode>
8
+ <App />
9
+ </StrictMode>,
10
+ )
frontend/my-app/src/pages/ChatPage.jsx ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useRef } from "react";
2
+ import { LuMic, LuRotateCcw } from "react-icons/lu";
3
+ import { API_BASE } from "../config";
4
+ const API = API_BASE || "http://localhost:8000";
5
+ import { authFetch, ensureGuestId, getGuestId, apiErrorMessage } from "../auth";
6
+ import { registerLocalFile } from "../localFileStore";
7
+ import { getNotesMirrorRoot, mirrorUploadedBytes } from "../localDiskFolder";
8
+ import { sanitizeVirtualPath } from "../virtualPath";
9
+ import "../index.css";
10
+
11
+ export default function ChatPage({ onSignInClick }) {
12
+ const makeSessionId = () =>
13
+ (typeof crypto !== "undefined" && crypto.randomUUID
14
+ ? crypto.randomUUID()
15
+ : `${Date.now()}-${Math.random().toString(36).slice(2)}`);
16
+ const [prompt, setPrompt] = useState("");
17
+ const [loading, setLoading] = useState(false);
18
+ const [message, setMessage] = useState(null);
19
+ const [listening, setListening] = useState(false);
20
+ const [chatSessionId, setChatSessionId] = useState(makeSessionId);
21
+ const fileInputRef = useRef(null);
22
+ const recognitionRef = useRef(null);
23
+
24
+ const handleUploadClick = () => {
25
+ fileInputRef.current?.click();
26
+ };
27
+
28
+ const handleFileChange = async (e) => {
29
+ const file = e.target.files?.[0];
30
+ if (!file) return;
31
+ e.target.value = "";
32
+ setLoading(true);
33
+ try {
34
+ const { root: mirrorRoot } = await getNotesMirrorRoot();
35
+ await ensureGuestId();
36
+ if (!getGuestId()) {
37
+ setMessage({ type: "error", text: "Could not connect to server. Is the backend running at http://localhost:8000?" });
38
+ setLoading(false);
39
+ return;
40
+ }
41
+ const formData = new FormData();
42
+ formData.append("chat_session_id", chatSessionId);
43
+ formData.append("file", file);
44
+ const res = await authFetch(`${API}/chat/upload_ephemeral`, {
45
+ method: "POST",
46
+ body: formData,
47
+ });
48
+ let data = {};
49
+ try {
50
+ data = await res.json();
51
+ } catch (_) {}
52
+ const rel = sanitizeVirtualPath(data.path || file.name || "");
53
+ if (rel && file) {
54
+ registerLocalFile(rel, file);
55
+ try {
56
+ await mirrorUploadedBytes(file, rel, mirrorRoot);
57
+ } catch (mirrorErr) {
58
+ console.error("Local mirror write failed:", mirrorErr);
59
+ }
60
+ }
61
+ if (res.ok) {
62
+ setMessage({ type: "success", text: `Uploaded "${file.name}" for this chat session only.` });
63
+ } else {
64
+ setMessage({ type: "error", text: apiErrorMessage(data, res) });
65
+ }
66
+ } catch (err) {
67
+ setMessage({
68
+ type: "error",
69
+ text: "Upload failed. Is the backend running? Start it with: uvicorn backend.api:app --host 0.0.0.0 --port 8000",
70
+ });
71
+ } finally {
72
+ setLoading(false);
73
+ }
74
+ };
75
+
76
+ const handleVoiceInput = () => {
77
+ const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
78
+ if (!SpeechRecognition) {
79
+ setMessage({ type: "error", text: "Voice input is not supported in this browser." });
80
+ return;
81
+ }
82
+ if (listening && recognitionRef.current) {
83
+ recognitionRef.current.stop();
84
+ return;
85
+ }
86
+ const rec = new SpeechRecognition();
87
+ rec.lang = "en-US";
88
+ rec.interimResults = false;
89
+ rec.maxAlternatives = 1;
90
+ rec.onstart = () => setListening(true);
91
+ rec.onresult = (event) => {
92
+ const spoken = event?.results?.[0]?.[0]?.transcript || "";
93
+ if (spoken.trim()) {
94
+ setPrompt((prev) => (prev ? `${prev} ${spoken}` : spoken));
95
+ }
96
+ };
97
+ rec.onerror = () => setListening(false);
98
+ rec.onend = () => {
99
+ setListening(false);
100
+ recognitionRef.current = null;
101
+ };
102
+ recognitionRef.current = rec;
103
+ rec.start();
104
+ };
105
+
106
+ const handleSubmit = (e) => {
107
+ e.preventDefault();
108
+ const text = prompt.trim();
109
+ if (!text) return;
110
+ setMessage({ type: "info", text: "Sign in to query your notes with AI. Use the Sign in button above." });
111
+ setPrompt("");
112
+ };
113
+
114
+ return (
115
+ <div className="chat-page">
116
+ <header className="chat-page-header">
117
+ <div className="chat-page-brand">NoteScanner</div>
118
+ <button type="button" className="auth-btn chat-page-signin" onClick={onSignInClick}>
119
+ Sign in
120
+ </button>
121
+ </header>
122
+
123
+ <main className="chat-page-main">
124
+ <h1 className="chat-page-title">Where should we begin?</h1>
125
+
126
+ <form className="chat-page-form" onSubmit={handleSubmit}>
127
+ <div className="chat-page-input-wrap">
128
+ <button
129
+ type="button"
130
+ className="chat-page-plus"
131
+ onClick={handleUploadClick}
132
+ title="Upload files or images"
133
+ aria-label="Upload"
134
+ >
135
+ +
136
+ </button>
137
+ <input
138
+ type="text"
139
+ className="chat-page-input"
140
+ placeholder="Ask anything"
141
+ value={prompt}
142
+ onChange={(e) => setPrompt(e.target.value)}
143
+ disabled={loading}
144
+ />
145
+ <button
146
+ type="button"
147
+ className={`chat-page-mic ${listening ? "chat-page-mic--active" : ""}`}
148
+ onClick={handleVoiceInput}
149
+ title={listening ? "Stop voice input" : "Voice input"}
150
+ aria-label={listening ? "Stop voice input" : "Voice input"}
151
+ >
152
+ <LuMic size={18} />
153
+ </button>
154
+ <button
155
+ type="button"
156
+ className="chat-page-mic"
157
+ onClick={async () => {
158
+ const fd = new FormData();
159
+ fd.append("chat_session_id", chatSessionId);
160
+ await authFetch(`${API}/chat/session/clear`, { method: "POST", body: fd }).catch(() => {});
161
+ setChatSessionId(makeSessionId());
162
+ setMessage({ type: "info", text: "Chat cache cleared." });
163
+ }}
164
+ title="Refresh chat"
165
+ aria-label="Refresh chat"
166
+ >
167
+ <LuRotateCcw size={18} />
168
+ </button>
169
+ </div>
170
+ {message && (
171
+ <p className={`chat-page-message chat-page-message--${message.type}`}>
172
+ {message.text}
173
+ </p>
174
+ )}
175
+ </form>
176
+
177
+ <div className="chat-page-suggestions">
178
+ <button type="button" className="chat-page-suggestion" onClick={() => setPrompt("Summarize my notes")}>
179
+ Summarize my notes
180
+ </button>
181
+ <button type="button" className="chat-page-suggestion" onClick={() => setPrompt("Explain this concept")}>
182
+ Explain this concept
183
+ </button>
184
+ <button type="button" className="chat-page-suggestion" onClick={() => setPrompt("Quiz me on my notes")}>
185
+ Quiz me on my notes
186
+ </button>
187
+ <button type="button" className="chat-page-suggestion" onClick={() => setPrompt("Find key points")}>
188
+ Find key points
189
+ </button>
190
+ </div>
191
+ </main>
192
+
193
+ <input
194
+ ref={fileInputRef}
195
+ type="file"
196
+ accept="image/*,.pdf"
197
+ onChange={handleFileChange}
198
+ style={{ display: "none" }}
199
+ aria-hidden
200
+ />
201
+ </div>
202
+ );
203
+ }
frontend/my-app/src/pages/Home.jsx ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useRef, useEffect, useCallback } from "react";
2
+ import Explorer from "../components/Explorer";
3
+ import QueryInterface from "../components/QueryInterface";
4
+ import StudyPanel from "../components/StudyPanel";
5
+ import { getUserName, setUserName, authFetch } from "../auth";
6
+ import { registerLocalFile, getBlobUrlForPath } from "../localFileStore";
7
+ import { hydrateLocalPreviewFromMirror } from "../localDiskFolder";
8
+ import { API_BASE } from "../config";
9
+ import "../index.css";
10
+ import { HiOutlineUserCircle } from "react-icons/hi2";
11
+
12
+ const LS_LEFT_W = "notescanner-left-sidebar-w";
13
+ const LS_RIGHT_W = "notescanner-right-sidebar-w";
14
+
15
+ const LEFT_W_MIN = 150;
16
+ const LEFT_W_MAX = 480;
17
+ const RIGHT_W_MIN = 200;
18
+ const RIGHT_W_MAX = 520;
19
+
20
+ function readLeftSidebarWidth() {
21
+ try {
22
+ const n = parseInt(localStorage.getItem(LS_LEFT_W) || "", 10);
23
+ if (Number.isFinite(n)) return Math.min(LEFT_W_MAX, Math.max(LEFT_W_MIN, n));
24
+ } catch {
25
+ /* ignore */
26
+ }
27
+ return 250;
28
+ }
29
+
30
+ function readRightSidebarWidth() {
31
+ try {
32
+ const n = parseInt(localStorage.getItem(LS_RIGHT_W) || "", 10);
33
+ if (Number.isFinite(n)) return Math.min(RIGHT_W_MAX, Math.max(RIGHT_W_MIN, n));
34
+ } catch {
35
+ /* ignore */
36
+ }
37
+ return 300;
38
+ }
39
+
40
+ export default function Home({ onLogout, onSignInClick, signedIn }) {
41
+ const [preview, setPreview] = useState(null);
42
+ const [previewHydrating, setPreviewHydrating] = useState(false);
43
+ const [profileOpen, setProfileOpen] = useState(false);
44
+ const [leftSidebarPx, setLeftSidebarPx] = useState(readLeftSidebarWidth);
45
+ const [rightSidebarPx, setRightSidebarPx] = useState(readRightSidebarWidth);
46
+ const profileRef = useRef(null);
47
+ const leftSidebarRef = useRef(null);
48
+ const rightSidebarRef = useRef(null);
49
+ const previewAttachRef = useRef(null);
50
+
51
+ useEffect(() => {
52
+ const handleClickOutside = (e) => {
53
+ if (profileRef.current && !profileRef.current.contains(e.target)) {
54
+ setProfileOpen(false);
55
+ }
56
+ };
57
+ document.addEventListener("click", handleClickOutside);
58
+ return () => document.removeEventListener("click", handleClickOutside);
59
+ }, []);
60
+
61
+ useEffect(() => {
62
+ if (!signedIn) return;
63
+ if (getUserName()) return;
64
+ authFetch(`${API_BASE}/me`)
65
+ .then((res) => (res.ok ? res.json() : null))
66
+ .then((data) => {
67
+ if (data?.name) setUserName(data.name);
68
+ })
69
+ .catch(() => {});
70
+ }, [signedIn]);
71
+
72
+ const handleFileSelect = useCallback((fileUrl, name, path) => {
73
+ const url = fileUrl || getBlobUrlForPath(path) || null;
74
+ setPreview({ url, name, path });
75
+ }, []);
76
+
77
+ useEffect(() => {
78
+ if (!preview?.path || preview?.url) return;
79
+ const pathToLoad = preview.path;
80
+ let cancelled = false;
81
+ setPreviewHydrating(true);
82
+ (async () => {
83
+ try {
84
+ const url = await hydrateLocalPreviewFromMirror(pathToLoad);
85
+ if (cancelled) return;
86
+ if (url) {
87
+ setPreview((p) => (p?.path === pathToLoad ? { ...p, url } : p));
88
+ }
89
+ } finally {
90
+ if (!cancelled) setPreviewHydrating(false);
91
+ }
92
+ })();
93
+ return () => {
94
+ cancelled = true;
95
+ };
96
+ }, [preview?.path, preview?.url]);
97
+
98
+ const handlePreviewAttach = (e) => {
99
+ const file = e.target.files?.[0];
100
+ e.target.value = "";
101
+ if (!file || !preview?.path) return;
102
+ registerLocalFile(preview.path, file);
103
+ setPreview((p) =>
104
+ p ? { ...p, url: getBlobUrlForPath(p.path), name: file.name || p.name } : null,
105
+ );
106
+ };
107
+
108
+ /** Width updates go straight to the DOM during drag; React state commits on pointer up (smooth, no child re-renders per frame). */
109
+ const handleLeftResizerPointerDown = (e) => {
110
+ if (e.pointerType === "mouse" && e.button !== 0) return;
111
+ e.preventDefault();
112
+ const handle = e.currentTarget;
113
+ handle.setPointerCapture(e.pointerId);
114
+ handle.classList.add("pane-resizer--active");
115
+
116
+ const startX = e.clientX;
117
+ const pane = leftSidebarRef.current;
118
+ const startW = pane?.getBoundingClientRect().width ?? leftSidebarPx;
119
+
120
+ const applyWidth = (w) => {
121
+ const clamped = Math.min(LEFT_W_MAX, Math.max(LEFT_W_MIN, w));
122
+ if (pane) pane.style.width = `${clamped}px`;
123
+ return clamped;
124
+ };
125
+
126
+ const onMove = (ev) => {
127
+ if (ev.pointerId !== e.pointerId) return;
128
+ const dx = ev.clientX - startX;
129
+ applyWidth(startW + dx);
130
+ };
131
+
132
+ const finish = (ev) => {
133
+ if (ev.pointerId !== e.pointerId) return;
134
+ try {
135
+ handle.releasePointerCapture(e.pointerId);
136
+ } catch {
137
+ /* ignore */
138
+ }
139
+ handle.classList.remove("pane-resizer--active");
140
+ handle.removeEventListener("pointermove", onMove);
141
+ handle.removeEventListener("pointerup", finish);
142
+ handle.removeEventListener("pointercancel", finish);
143
+ document.body.style.removeProperty("cursor");
144
+ document.body.style.removeProperty("user-select");
145
+
146
+ const w = Math.round(
147
+ pane?.getBoundingClientRect().width ??
148
+ Math.min(LEFT_W_MAX, Math.max(LEFT_W_MIN, startW)),
149
+ );
150
+ const clamped = Math.min(LEFT_W_MAX, Math.max(LEFT_W_MIN, w));
151
+ setLeftSidebarPx(clamped);
152
+ if (pane) pane.style.width = `${clamped}px`;
153
+ try {
154
+ localStorage.setItem(LS_LEFT_W, String(clamped));
155
+ } catch {
156
+ /* ignore */
157
+ }
158
+ };
159
+
160
+ document.body.style.cursor = "col-resize";
161
+ document.body.style.userSelect = "none";
162
+ handle.addEventListener("pointermove", onMove);
163
+ handle.addEventListener("pointerup", finish);
164
+ handle.addEventListener("pointercancel", finish);
165
+ };
166
+
167
+ const handleRightResizerPointerDown = (e) => {
168
+ if (e.pointerType === "mouse" && e.button !== 0) return;
169
+ e.preventDefault();
170
+ const handle = e.currentTarget;
171
+ handle.setPointerCapture(e.pointerId);
172
+ handle.classList.add("pane-resizer--active");
173
+
174
+ const startX = e.clientX;
175
+ const pane = rightSidebarRef.current;
176
+ const startW = pane?.getBoundingClientRect().width ?? rightSidebarPx;
177
+
178
+ const applyWidth = (w) => {
179
+ const clamped = Math.min(RIGHT_W_MAX, Math.max(RIGHT_W_MIN, w));
180
+ if (pane) pane.style.width = `${clamped}px`;
181
+ return clamped;
182
+ };
183
+
184
+ const onMove = (ev) => {
185
+ if (ev.pointerId !== e.pointerId) return;
186
+ const dx = startX - ev.clientX;
187
+ applyWidth(startW + dx);
188
+ };
189
+
190
+ const finish = (ev) => {
191
+ if (ev.pointerId !== e.pointerId) return;
192
+ try {
193
+ handle.releasePointerCapture(e.pointerId);
194
+ } catch {
195
+ /* ignore */
196
+ }
197
+ handle.classList.remove("pane-resizer--active");
198
+ handle.removeEventListener("pointermove", onMove);
199
+ handle.removeEventListener("pointerup", finish);
200
+ handle.removeEventListener("pointercancel", finish);
201
+ document.body.style.removeProperty("cursor");
202
+ document.body.style.removeProperty("user-select");
203
+
204
+ const w = Math.round(
205
+ pane?.getBoundingClientRect().width ??
206
+ Math.min(RIGHT_W_MAX, Math.max(RIGHT_W_MIN, startW)),
207
+ );
208
+ const clamped = Math.min(RIGHT_W_MAX, Math.max(RIGHT_W_MIN, w));
209
+ setRightSidebarPx(clamped);
210
+ if (pane) pane.style.width = `${clamped}px`;
211
+ try {
212
+ localStorage.setItem(LS_RIGHT_W, String(clamped));
213
+ } catch {
214
+ /* ignore */
215
+ }
216
+ };
217
+
218
+ document.body.style.cursor = "col-resize";
219
+ document.body.style.userSelect = "none";
220
+ handle.addEventListener("pointermove", onMove);
221
+ handle.addEventListener("pointerup", finish);
222
+ handle.addEventListener("pointercancel", finish);
223
+ };
224
+
225
+ const isPdf = preview?.name?.toLowerCase().endsWith(".pdf");
226
+ const activeFilePath = preview?.path || "";
227
+ const activeCourseFolder = activeFilePath.includes("/")
228
+ ? activeFilePath.split("/")[0]
229
+ : activeFilePath;
230
+
231
+ return (
232
+ <div className="app-container">
233
+ <div className="app-header">
234
+ {signedIn ? (
235
+ <div className="profile-wrap" ref={profileRef}>
236
+ <button
237
+ type="button"
238
+ className="profile-trigger"
239
+ onClick={() => setProfileOpen((o) => !o)}
240
+ title="Profile"
241
+ aria-label="Profile"
242
+ aria-expanded={profileOpen}
243
+ aria-haspopup="true"
244
+ >
245
+ <HiOutlineUserCircle size={24} />
246
+ </button>
247
+ {profileOpen && (
248
+ <div className="profile-dropdown">
249
+ <div className="profile-dropdown-name">{getUserName() || "User"}</div>
250
+ <button
251
+ type="button"
252
+ className="profile-dropdown-signout"
253
+ onClick={() => {
254
+ setProfileOpen(false);
255
+ onLogout();
256
+ }}
257
+ >
258
+ Sign out
259
+ </button>
260
+ </div>
261
+ )}
262
+ </div>
263
+ ) : (
264
+ <button type="button" className="auth-btn" onClick={onSignInClick}>
265
+ Sign in
266
+ </button>
267
+ )}
268
+ </div>
269
+
270
+ <div className="app-main-row">
271
+ <div
272
+ ref={leftSidebarRef}
273
+ className="left-sidebar"
274
+ style={{ width: leftSidebarPx }}
275
+ >
276
+ <div className="left-sidebar-content">
277
+ <Explorer
278
+ onFileSelect={handleFileSelect}
279
+ onDeletePath={(path, isFolder) => {
280
+ if (
281
+ preview?.path &&
282
+ (preview.path === path ||
283
+ (isFolder && preview.path.startsWith(`${path}/`)))
284
+ ) {
285
+ setPreview(null);
286
+ }
287
+ }}
288
+ onMovePath={(from, to, isFolder) => {
289
+ if (!preview?.path || !to) return;
290
+ if (!isFolder && preview.path === from) {
291
+ setPreview((p) => (p ? { ...p, path: to } : null));
292
+ return;
293
+ }
294
+ if (isFolder && preview.path.startsWith(`${from}/`)) {
295
+ setPreview((p) =>
296
+ p
297
+ ? {
298
+ ...p,
299
+ path: `${to}/${p.path.slice(from.length + 1)}`,
300
+ }
301
+ : null,
302
+ );
303
+ }
304
+ }}
305
+ />
306
+ </div>
307
+ </div>
308
+
309
+ <div
310
+ className="pane-resizer pane-resizer--vertical"
311
+ onPointerDown={handleLeftResizerPointerDown}
312
+ role="separator"
313
+ aria-orientation="vertical"
314
+ aria-label="Resize file explorer and preview"
315
+ title="Drag to resize"
316
+ />
317
+
318
+ <div className="preview-pane">
319
+ <div className="preview-content">
320
+ {preview?.url ? (
321
+ isPdf ? (
322
+ <embed
323
+ src={preview.url}
324
+ type="application/pdf"
325
+ title={preview.name || "PDF"}
326
+ />
327
+ ) : (
328
+ <img src={preview.url} alt="preview" />
329
+ )
330
+ ) : previewHydrating ? (
331
+ <div className="preview-placeholder">
332
+ <div className="preview-placeholder-icon">📄</div>
333
+ <p>Opening from your NoteScanner folder…</p>
334
+ </div>
335
+ ) : preview?.path ? (
336
+ <div className="preview-placeholder">
337
+ <div className="preview-placeholder-icon">📄</div>
338
+ <p>
339
+ No copy of this file was found in your linked NoteScanner folder. Upload it again
340
+ or choose the file below (metadata and search stay in the cloud database).
341
+ </p>
342
+ <input
343
+ ref={previewAttachRef}
344
+ type="file"
345
+ accept="image/*,.pdf,application/pdf"
346
+ className="preview-attach-input"
347
+ aria-hidden
348
+ tabIndex={-1}
349
+ onChange={handlePreviewAttach}
350
+ />
351
+ <button
352
+ type="button"
353
+ className="preview-attach-btn"
354
+ onClick={() => previewAttachRef.current?.click()}
355
+ >
356
+ Choose file…
357
+ </button>
358
+ </div>
359
+ ) : (
360
+ <div className="preview-placeholder">
361
+ <div className="preview-placeholder-icon">📄</div>
362
+ <p>Select a file from the explorer to preview it here</p>
363
+ </div>
364
+ )}
365
+ </div>
366
+ </div>
367
+
368
+ <div
369
+ className="pane-resizer pane-resizer--vertical"
370
+ onPointerDown={handleRightResizerPointerDown}
371
+ role="separator"
372
+ aria-orientation="vertical"
373
+ aria-label="Resize preview and chat panels"
374
+ title="Drag to resize"
375
+ />
376
+
377
+ <div
378
+ ref={rightSidebarRef}
379
+ className="right-sidebar"
380
+ style={{ width: rightSidebarPx }}
381
+ >
382
+ <div className="right-sidebar-content">
383
+ <QueryInterface
384
+ activeFilePath={activeFilePath}
385
+ activeCourseFolder={activeCourseFolder}
386
+ />
387
+ <StudyPanel
388
+ activeFilePath={activeFilePath}
389
+ activeCourseFolder={activeCourseFolder}
390
+ />
391
+ </div>
392
+ </div>
393
+ </div>
394
+ </div>
395
+ );
396
+ }
frontend/my-app/src/pages/Login.jsx ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from "react";
2
+ import { API_BASE } from "../config";
3
+ import { setSessionId } from "../auth";
4
+ import "../index.css";
5
+
6
+ export default function Login({ onLogin, onSwitchToRegister, onClose }) {
7
+ const [email, setEmail] = useState("");
8
+ const [password, setPassword] = useState("");
9
+ const [error, setError] = useState("");
10
+ const [loading, setLoading] = useState(false);
11
+
12
+ const handleSubmit = async (e) => {
13
+ e.preventDefault();
14
+ setError("");
15
+ setLoading(true);
16
+ try {
17
+ const formData = new FormData();
18
+ formData.append("email", email);
19
+ formData.append("password", password);
20
+ const res = await fetch(`${API_BASE}/login`, {
21
+ method: "POST",
22
+ body: formData,
23
+ });
24
+ const data = await res.json();
25
+ if (!res.ok) {
26
+ setError(data.detail || data.error || "Login failed.");
27
+ return;
28
+ }
29
+ if (data.session_id) setSessionId(data.session_id, data.name ?? undefined);
30
+ onLogin?.();
31
+ } catch (err) {
32
+ setError("Network error. Please try again.");
33
+ } finally {
34
+ setLoading(false);
35
+ }
36
+ };
37
+
38
+ return (
39
+ <div className="auth-page">
40
+ <div className="auth-card">
41
+ <h1 className="auth-title">NoteScanner</h1>
42
+ <p className="auth-subtitle">Sign in to your account</p>
43
+ <form onSubmit={handleSubmit} className="auth-form">
44
+ <input
45
+ type="email"
46
+ placeholder="Email"
47
+ value={email}
48
+ onChange={(e) => setEmail(e.target.value)}
49
+ className="auth-input"
50
+ required
51
+ autoComplete="email"
52
+ />
53
+ <input
54
+ type="password"
55
+ placeholder="Password"
56
+ value={password}
57
+ onChange={(e) => setPassword(e.target.value)}
58
+ className="auth-input"
59
+ required
60
+ autoComplete="current-password"
61
+ />
62
+ {error && <p className="auth-error">{error}</p>}
63
+ <button type="submit" className="auth-btn" disabled={loading}>
64
+ {loading ? "Signing in…" : "Sign in"}
65
+ </button>
66
+ </form>
67
+ <p className="auth-switch">
68
+ Don’t have an account?{" "}
69
+ <button type="button" onClick={onSwitchToRegister} className="auth-link">
70
+ Sign up
71
+ </button>
72
+ </p>
73
+ {onClose && (
74
+ <button type="button" className="auth-close" onClick={onClose} aria-label="Close">
75
+ ×
76
+ </button>
77
+ )}
78
+ </div>
79
+ </div>
80
+ );
81
+ }
frontend/my-app/src/pages/Register.jsx ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from "react";
2
+ import { API_BASE } from "../config";
3
+ import { setSessionId } from "../auth";
4
+ import "../index.css";
5
+
6
+ export default function Register({ onRegister, onSwitchToLogin, onClose }) {
7
+ const [email, setEmail] = useState("");
8
+ const [password, setPassword] = useState("");
9
+ const [name, setName] = useState("");
10
+ const [error, setError] = useState("");
11
+ const [loading, setLoading] = useState(false);
12
+
13
+ const handleSubmit = async (e) => {
14
+ e.preventDefault();
15
+ setError("");
16
+ setLoading(true);
17
+ try {
18
+ const formData = new FormData();
19
+ formData.append("email", email);
20
+ formData.append("password", password);
21
+ formData.append("name", name);
22
+ const url = `${API_BASE || "http://localhost:8000"}/register`;
23
+ const res = await fetch(url, {
24
+ method: "POST",
25
+ body: formData,
26
+ });
27
+ let data = {};
28
+ try {
29
+ data = await res.json();
30
+ } catch (_) {
31
+ if (!res.ok) setError(res.statusText || "Registration failed.");
32
+ return;
33
+ }
34
+ if (!res.ok) {
35
+ setError(data.detail || data.error || "Registration failed.");
36
+ return;
37
+ }
38
+ if (data.session_id) setSessionId(data.session_id, data.name ?? undefined);
39
+ onRegister?.();
40
+ } catch (err) {
41
+ const msg = err?.message || "";
42
+ setError(
43
+ API_BASE
44
+ ? "Network error. Is the backend running? Start it with: uvicorn backend.api:app --host 0.0.0.0 --port 8000"
45
+ : "Network error. Set VITE_API_URL=http://localhost:8000 and ensure the backend is running."
46
+ );
47
+ } finally {
48
+ setLoading(false);
49
+ }
50
+ };
51
+
52
+ return (
53
+ <div className="auth-page">
54
+ <div className="auth-card">
55
+ <h1 className="auth-title">NoteScanner</h1>
56
+ <p className="auth-subtitle">Create an account</p>
57
+ <form onSubmit={handleSubmit} className="auth-form">
58
+ <input
59
+ type="email"
60
+ placeholder="Email"
61
+ value={email}
62
+ onChange={(e) => setEmail(e.target.value)}
63
+ className="auth-input"
64
+ required
65
+ autoComplete="email"
66
+ />
67
+ <input
68
+ type="text"
69
+ placeholder="Name (optional)"
70
+ value={name}
71
+ onChange={(e) => setName(e.target.value)}
72
+ className="auth-input"
73
+ autoComplete="name"
74
+ />
75
+ <input
76
+ type="password"
77
+ placeholder="Password"
78
+ value={password}
79
+ onChange={(e) => setPassword(e.target.value)}
80
+ className="auth-input"
81
+ required
82
+ minLength={6}
83
+ autoComplete="new-password"
84
+ />
85
+ {error && <p className="auth-error">{error}</p>}
86
+ <button type="submit" className="auth-btn" disabled={loading}>
87
+ {loading ? "Creating account…" : "Sign up"}
88
+ </button>
89
+ </form>
90
+ <p className="auth-switch">
91
+ Already have an account?{" "}
92
+ <button type="button" onClick={onSwitchToLogin} className="auth-link">
93
+ Sign in
94
+ </button>
95
+ </p>
96
+ {onClose && (
97
+ <button type="button" className="auth-close" onClick={onClose} aria-label="Close">
98
+ ×
99
+ </button>
100
+ )}
101
+ </div>
102
+ </div>
103
+ );
104
+ }
frontend/my-app/src/virtualPath.js ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Aligns with backend _strip_storage_path: virtual paths are course/file only,
3
+ * never user_notes/ or legacy per-user id segments (so disk mirror stays under NoteScanner).
4
+ */
5
+
6
+ function isUuidLike(seg) {
7
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(seg);
8
+ }
9
+
10
+ export function sanitizeVirtualPath(p) {
11
+ if (p == null || p === "") return "";
12
+ let parts = String(p)
13
+ .replace(/\\/g, "/")
14
+ .replace(/^\/+|\/+$/g, "")
15
+ .split("/")
16
+ .filter((x) => x && x !== ".");
17
+ while (parts.length && parts[0].toLowerCase() === "user_notes") {
18
+ parts.shift();
19
+ }
20
+ if (parts.length && /^guest_/i.test(parts[0])) parts.shift();
21
+ else if (parts.length && isUuidLike(parts[0])) parts.shift();
22
+ return parts.join("/");
23
+ }
frontend/my-app/vite.config.js ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import { defineConfig } from 'vite'
2
+ import react from '@vitejs/plugin-react'
3
+
4
+ // https://vite.dev/config/
5
+ export default defineConfig({
6
+ plugins: [react()],
7
+ base: '/NoteScanner/',
8
+ })
requirements.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ langchain
4
+ langchain-community
5
+ langchain-chroma
6
+ langchain-text-splitters
7
+ httpx>=0.27.0
8
+ sarvamai>=0.1.27
9
+ pytesseract
10
+ pillow
11
+ python-dotenv
12
+ transformers
13
+ torch
14
+ sentence-transformers
15
+ chromadb>=1.0.0
16
+ pymupdf
17
+ python-multipart
18
+ passlib[bcrypt]
19
+ bcrypt>=4.0,<4.1