Rsukesh001 commited on
Commit
3beb728
Β·
verified Β·
1 Parent(s): 2498423

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +893 -395
README.md CHANGED
@@ -1,395 +1,893 @@
1
- # πŸŽ“ Smart StudyMate - Complete Setup Guide for VS Code
2
-
3
- ## πŸ“‹ Prerequisites
4
-
5
- - Windows 10/11, macOS, or Linux
6
- - Python 3.8 or higher
7
- - VS Code installed
8
- - At least 8GB RAM (for running LLaMA 3.1)
9
- - 10GB free disk space
10
-
11
- ---
12
-
13
- ## πŸš€ Step-by-Step Installation
14
-
15
- ### **Step 1: Install Python**
16
-
17
- #### Windows:
18
- 1. Download Python from: https://www.python.org/downloads/
19
- 2. Run installer and **CHECK** "Add Python to PATH"
20
- 3. Verify installation:
21
- ```bash
22
- python --version
23
- ```
24
-
25
- #### Mac/Linux:
26
- ```bash
27
- # Mac (using Homebrew)
28
- brew install python
29
-
30
- # Linux
31
- sudo apt update
32
- sudo apt install python3 python3-pip
33
- ```
34
-
35
- ---
36
-
37
- ### **Step 2: Install VS Code Extensions**
38
-
39
- Open VS Code and install:
40
- 1. **Python** (by Microsoft)
41
- 2. **Pylance** (by Microsoft)
42
-
43
- ---
44
-
45
- ### **Step 3: Create Project Folder**
46
-
47
- ```bash
48
- # Open terminal in VS Code (Ctrl + ` or Cmd + `)
49
- mkdir smart-studymate
50
- cd smart-studymate
51
- ```
52
-
53
- ---
54
-
55
- ### **Step 4: Create Virtual Environment**
56
-
57
- ```bash
58
- # Create virtual environment
59
- python -m venv venv
60
-
61
- # Activate it
62
- # Windows:
63
- venv\Scripts\activate
64
-
65
- # Mac/Linux:
66
- source venv/bin/activate
67
- ```
68
-
69
- You should see `(venv)` in your terminal now.
70
-
71
- ---
72
-
73
- ### **Step 5: Install Python Dependencies**
74
-
75
- Create a file called `requirements.txt`:
76
-
77
- ```txt
78
- flask==3.0.0
79
- sentence-transformers==2.2.2
80
- faiss-cpu==1.7.4
81
- PyPDF2==3.0.1
82
- python-docx==1.1.0
83
- python-pptx==0.6.23
84
- langchain==0.1.0
85
- langchain-community==0.0.13
86
- numpy==1.24.3
87
- ```
88
-
89
- Install all dependencies:
90
- ```bash
91
- pip install -r requirements.txt
92
- ```
93
-
94
- ---
95
-
96
- ### **Step 6: Install Ollama**
97
-
98
- #### Windows:
99
- 1. Download from: https://ollama.ai/download
100
- 2. Run the installer
101
- 3. Verify installation:
102
- ```bash
103
- ollama --version
104
- ```
105
-
106
- #### Mac:
107
- ```bash
108
- brew install ollama
109
- ```
110
-
111
- #### Linux:
112
- ```bash
113
- curl -fsSL https://ollama.ai/install.sh | sh
114
- ```
115
-
116
- ---
117
-
118
- ### **Step 7: Download LLaMA 3.1 Model**
119
-
120
- ```bash
121
- # This will download ~4.7GB
122
- ollama pull llama3.1:8b
123
- ```
124
-
125
- Wait for download to complete. Verify:
126
- ```bash
127
- ollama list
128
- ```
129
-
130
- You should see `llama3.1:8b` in the list.
131
-
132
- ---
133
-
134
- ### **Step 8: Create Project Files**
135
-
136
- Create this folder structure:
137
-
138
- ```
139
- smart-studymate/
140
- β”œβ”€β”€ app.py (main application)
141
- β”œβ”€β”€ requirements.txt (dependencies)
142
- β”œβ”€β”€ uploads/ (auto-created for uploaded files)
143
- β”œβ”€β”€ faiss_index/ (auto-created for vector storage)
144
- └── venv/ (virtual environment)
145
- ```
146
-
147
- ---
148
-
149
- ### **Step 9: Create app.py**
150
-
151
- Copy the entire Python code I provided earlier into `app.py`.
152
-
153
- In VS Code:
154
- 1. File β†’ New File
155
- 2. Save as `app.py`
156
- 3. Paste the complete code
157
-
158
- ---
159
-
160
- ### **Step 10: Start Ollama Service**
161
-
162
- **IMPORTANT**: Ollama must be running before starting the app!
163
-
164
- #### Windows/Mac:
165
- Ollama runs automatically after installation. Check system tray.
166
-
167
- #### Linux:
168
- ```bash
169
- ollama serve
170
- ```
171
-
172
- Keep this terminal open.
173
-
174
- ---
175
-
176
- ### **Step 11: Run the Application**
177
-
178
- Open a new terminal in VS Code and run:
179
-
180
- ```bash
181
- # Make sure virtual environment is activated
182
- # You should see (venv) in terminal
183
-
184
- python app.py
185
- ```
186
-
187
- You should see:
188
- ```
189
- ============================================================
190
- πŸŽ“ Smart StudyMate - AI Study Assistant
191
- ============================================================
192
-
193
- Starting server...
194
- πŸ“Œ Access the application at: http://localhost:5000
195
-
196
- ⚠️ Make sure Ollama is running with LLaMA 3.1 8B model!
197
- Run: ollama pull llama3.1:8b
198
- ============================================================
199
- ```
200
-
201
- ---
202
-
203
- ### **Step 12: Access the Application**
204
-
205
- Open your browser and go to:
206
- ```
207
- http://localhost:5000
208
- ```
209
-
210
- ---
211
-
212
- ## 🎯 Testing the Application
213
-
214
- ### **1. Upload a Document**
215
- 1. Click "Choose File"
216
- 2. Select a PDF/DOCX/TXT/PPTX file
217
- 3. Click "Upload & Process"
218
- 4. Wait for processing (you'll see chunks created)
219
-
220
- ### **2. Ask Questions**
221
- 1. Make sure "Ask Questions" mode is selected
222
- 2. Type a question about your notes
223
- 3. Click "Send"
224
- 4. Wait for AI response
225
-
226
- ### **3. Generate Summary**
227
- 1. Click "Summarize" mode
228
- 2. Enter topic (or leave empty)
229
- 3. Click "Send"
230
-
231
- ### **4. Generate MCQs**
232
- 1. Click "Generate MCQs" mode
233
- 2. Enter topic (or leave empty)
234
- 3. Click "Send"
235
-
236
- ---
237
-
238
- ## πŸ”§ Troubleshooting
239
-
240
- ### **Problem: ModuleNotFoundError**
241
- **Solution:**
242
- ```bash
243
- # Make sure virtual environment is activated
244
- # Check if (venv) appears in terminal
245
- pip install -r requirements.txt
246
- ```
247
-
248
- ### **Problem: Ollama connection error**
249
- **Solution:**
250
- ```bash
251
- # Check if Ollama is running
252
- ollama list
253
-
254
- # If not, start it
255
- ollama serve
256
- ```
257
-
258
- ### **Problem: "No module named 'langchain_community'"**
259
- **Solution:**
260
- ```bash
261
- pip install langchain-community
262
- ```
263
-
264
- ### **Problem: Port 5000 already in use**
265
- **Solution:**
266
- Change port in `app.py` (last line):
267
- ```python
268
- app.run(debug=True, host='0.0.0.0', port=5001)
269
- ```
270
-
271
- ### **Problem: FAISS installation error**
272
- **Solution:**
273
- ```bash
274
- # For Windows with issues, try:
275
- pip install faiss-cpu --no-cache-dir
276
-
277
- # Or use conda
278
- conda install -c pytorch faiss-cpu
279
- ```
280
-
281
- ### **Problem: Slow responses**
282
- **Causes:**
283
- - LLaMA 3.1 requires good CPU/GPU
284
- - First query is slower (model loading)
285
- - Large documents take time
286
-
287
- **Solutions:**
288
- - Use smaller chunk sizes
289
- - Reduce `top_k` in retrieval
290
- - Use a smaller model: `ollama pull llama3.1:8b`
291
-
292
- ---
293
-
294
- ## πŸ“Š Checking Logs
295
-
296
- VS Code terminal will show:
297
- - File uploads
298
- - Processing status
299
- - FAISS index updates
300
- - API requests
301
- - Errors (if any)
302
-
303
- ---
304
-
305
- ## πŸ›‘ Stopping the Application
306
-
307
- Press `Ctrl + C` in the terminal running `app.py`
308
-
309
- ---
310
-
311
- ## πŸ’Ύ Data Persistence
312
-
313
- Your data is saved in:
314
- - `faiss_index/index.faiss` - Vector embeddings
315
- - `faiss_index/metadata.pkl` - Chunk metadata
316
- - `uploads/` - Uploaded files
317
-
318
- **To reset everything:**
319
- ```bash
320
- # Delete these folders
321
- rm -rf faiss_index uploads
322
- ```
323
-
324
- ---
325
-
326
- ## πŸŽ“ Sample Test Document
327
-
328
- Create a test file `test_notes.txt`:
329
-
330
- ```txt
331
- Artificial Intelligence
332
-
333
- Machine Learning is a subset of AI that enables computers to learn from data.
334
-
335
- Types of Machine Learning:
336
- 1. Supervised Learning - Uses labeled data
337
- 2. Unsupervised Learning - Finds patterns in unlabeled data
338
- 3. Reinforcement Learning - Learns through trial and error
339
-
340
- Neural Networks are inspired by the human brain and consist of layers of interconnected nodes.
341
-
342
- Deep Learning uses neural networks with multiple layers to process complex data.
343
- ```
344
-
345
- Upload this and test with questions like:
346
- - "What is machine learning?"
347
- - "What are the types of machine learning?"
348
- - "Explain neural networks"
349
-
350
- ---
351
-
352
- ## πŸ”₯ Pro Tips
353
-
354
- 1. **Upload multiple related documents** for better context
355
- 2. **Ask specific questions** for better answers
356
- 3. **Use summarize feature** to get quick overviews
357
- 4. **Generate MCQs** for self-testing
358
- 5. **Check stats** to see how many vectors are stored
359
-
360
- ---
361
-
362
- ## πŸ“± Accessing from Other Devices
363
-
364
- To access from other devices on the same network:
365
-
366
- 1. Find your IP address:
367
- ```bash
368
- # Windows
369
- ipconfig
370
-
371
- # Mac/Linux
372
- ifconfig
373
- ```
374
-
375
- 2. Change `app.py` last line:
376
- ```python
377
- app.run(debug=True, host='0.0.0.0', port=5000)
378
- ```
379
-
380
- 3. Access from other device:
381
- ```
382
- http://YOUR_IP_ADDRESS:5000
383
- ```
384
-
385
- ---
386
-
387
- ## πŸŽ‰ You're All Set!
388
-
389
- Your Smart StudyMate is now running locally with:
390
- - βœ… Local LLM (no API keys needed)
391
- - βœ… Persistent storage
392
- - βœ… Multi-format support
393
- - βœ… AI-powered features
394
-
395
- Happy studying! πŸ“šπŸš€
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify, render_template_string
2
+ from werkzeug.utils import secure_filename
3
+ import os
4
+ import PyPDF2
5
+ import docx
6
+ from pptx import Presentation
7
+ from sentence_transformers import SentenceTransformer
8
+ import faiss
9
+ import numpy as np
10
+ import pickle
11
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
12
+ from langchain_community.llms import Ollama
13
+ import json
14
+
15
+ app = Flask(__name__)
16
+ app.config['UPLOAD_FOLDER'] = 'uploads'
17
+ app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 # 50MB max file size
18
+ app.config['FAISS_INDEX_PATH'] = 'faiss_index'
19
+ app.config['METADATA_PATH'] = 'metadata.pkl'
20
+
21
+ # Create necessary directories
22
+ os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
23
+ os.makedirs(app.config['FAISS_INDEX_PATH'], exist_ok=True)
24
+
25
+ # Initialize models
26
+ print("Loading Sentence Transformer model...")
27
+ embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
28
+
29
+ print("Initializing Ollama LLaMA 3.1...")
30
+ llm = Ollama(model="llama3.1:8b", temperature=0.3)
31
+
32
+ # Global variables for FAISS index
33
+ faiss_index = None
34
+ metadata_store = []
35
+ dimension = 384 # all-MiniLM-L6-v2 embedding dimension
36
+
37
+ def load_faiss_index():
38
+ """Load existing FAISS index and metadata"""
39
+ global faiss_index, metadata_store
40
+
41
+ index_path = os.path.join(app.config['FAISS_INDEX_PATH'], 'index.faiss')
42
+ metadata_path = os.path.join(app.config['FAISS_INDEX_PATH'], app.config['METADATA_PATH'])
43
+
44
+ if os.path.exists(index_path) and os.path.exists(metadata_path):
45
+ faiss_index = faiss.read_index(index_path)
46
+ with open(metadata_path, 'rb') as f:
47
+ metadata_store = pickle.load(f)
48
+ print(f"Loaded FAISS index with {faiss_index.ntotal} vectors")
49
+ else:
50
+ faiss_index = faiss.IndexFlatL2(dimension)
51
+ metadata_store = []
52
+ print("Created new FAISS index")
53
+
54
+ def save_faiss_index():
55
+ """Save FAISS index and metadata persistently"""
56
+ index_path = os.path.join(app.config['FAISS_INDEX_PATH'], 'index.faiss')
57
+ metadata_path = os.path.join(app.config['FAISS_INDEX_PATH'], app.config['METADATA_PATH'])
58
+
59
+ faiss.write_index(faiss_index, index_path)
60
+ with open(metadata_path, 'wb') as f:
61
+ pickle.dump(metadata_store, f)
62
+ print(f"Saved FAISS index with {faiss_index.ntotal} vectors")
63
+
64
+ def extract_text_from_pdf(file_path):
65
+ """Extract text from PDF files"""
66
+ text = ""
67
+ with open(file_path, 'rb') as file:
68
+ pdf_reader = PyPDF2.PdfReader(file)
69
+ for page in pdf_reader.pages:
70
+ text += page.extract_text() + "\n"
71
+ return text
72
+
73
+ def extract_text_from_docx(file_path):
74
+ """Extract text from DOCX files"""
75
+ doc = docx.Document(file_path)
76
+ text = "\n".join([paragraph.text for paragraph in doc.paragraphs])
77
+ return text
78
+
79
+ def extract_text_from_txt(file_path):
80
+ """Extract text from TXT files"""
81
+ with open(file_path, 'r', encoding='utf-8', errors='ignore') as file:
82
+ text = file.read()
83
+ return text
84
+
85
+ def extract_text_from_pptx(file_path):
86
+ """Extract text from PPTX files"""
87
+ prs = Presentation(file_path)
88
+ text = ""
89
+ for slide in prs.slides:
90
+ for shape in slide.shapes:
91
+ if hasattr(shape, "text"):
92
+ text += shape.text + "\n"
93
+ return text
94
+
95
+ def extract_text(file_path, file_extension):
96
+ """Extract text based on file type"""
97
+ if file_extension == '.pdf':
98
+ return extract_text_from_pdf(file_path)
99
+ elif file_extension == '.docx':
100
+ return extract_text_from_docx(file_path)
101
+ elif file_extension == '.txt':
102
+ return extract_text_from_txt(file_path)
103
+ elif file_extension == '.pptx':
104
+ return extract_text_from_pptx(file_path)
105
+ else:
106
+ raise ValueError(f"Unsupported file type: {file_extension}")
107
+
108
+ def chunk_text(text, chunk_size=500):
109
+ """Split text into chunks using RecursiveCharacterTextSplitter"""
110
+ text_splitter = RecursiveCharacterTextSplitter(
111
+ chunk_size=chunk_size,
112
+ chunk_overlap=50,
113
+ length_function=len,
114
+ )
115
+ chunks = text_splitter.split_text(text)
116
+ return chunks
117
+
118
+ def add_to_faiss(chunks, filename):
119
+ """Add chunks to FAISS index with metadata"""
120
+ global faiss_index, metadata_store
121
+
122
+ embeddings = embedding_model.encode(chunks, show_progress_bar=True)
123
+ embeddings = np.array(embeddings).astype('float32')
124
+
125
+ # Add to FAISS index
126
+ faiss_index.add(embeddings)
127
+
128
+ # Store metadata
129
+ for i, chunk in enumerate(chunks):
130
+ metadata_store.append({
131
+ 'filename': filename,
132
+ 'chunk_id': len(metadata_store),
133
+ 'text': chunk
134
+ })
135
+
136
+ save_faiss_index()
137
+
138
+ def retrieve_relevant_chunks(query, top_k=5):
139
+ """Retrieve top-k relevant chunks from FAISS"""
140
+ if faiss_index.ntotal == 0:
141
+ return []
142
+
143
+ query_embedding = embedding_model.encode([query])
144
+ query_embedding = np.array(query_embedding).astype('float32')
145
+
146
+ distances, indices = faiss_index.search(query_embedding, min(top_k, faiss_index.ntotal))
147
+
148
+ results = []
149
+ for idx in indices[0]:
150
+ if idx < len(metadata_store):
151
+ results.append(metadata_store[idx])
152
+
153
+ return results
154
+
155
+ @app.route('/')
156
+ def index():
157
+ """Render the main chat interface"""
158
+ return render_template_string(HTML_TEMPLATE)
159
+
160
+ @app.route('/upload', methods=['POST'])
161
+ def upload_file():
162
+ """Upload and process files"""
163
+ if 'file' not in request.files:
164
+ return jsonify({'error': 'No file provided'}), 400
165
+
166
+ file = request.files['file']
167
+ if file.filename == '':
168
+ return jsonify({'error': 'No file selected'}), 400
169
+
170
+ filename = secure_filename(file.filename)
171
+ file_extension = os.path.splitext(filename)[1].lower()
172
+
173
+ if file_extension not in ['.pdf', '.docx', '.txt', '.pptx']:
174
+ return jsonify({'error': 'Unsupported file type. Please upload PDF, DOCX, TXT, or PPTX'}), 400
175
+
176
+ try:
177
+ # Save file
178
+ file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
179
+ file.save(file_path)
180
+
181
+ # Extract text
182
+ text = extract_text(file_path, file_extension)
183
+
184
+ if not text.strip():
185
+ return jsonify({'error': 'No text could be extracted from the file'}), 400
186
+
187
+ # Chunk text
188
+ chunks = chunk_text(text)
189
+
190
+ # Add to FAISS
191
+ add_to_faiss(chunks, filename)
192
+
193
+ return jsonify({
194
+ 'message': f'Successfully uploaded and processed {filename}',
195
+ 'chunks_created': len(chunks),
196
+ 'total_vectors': faiss_index.ntotal
197
+ }), 200
198
+
199
+ except Exception as e:
200
+ return jsonify({'error': str(e)}), 500
201
+
202
+ @app.route('/ask', methods=['POST'])
203
+ def ask_question():
204
+ """Answer questions based on uploaded notes"""
205
+ data = request.get_json()
206
+ question = data.get('question', '')
207
+
208
+ if not question:
209
+ return jsonify({'error': 'No question provided'}), 400
210
+
211
+ if faiss_index.ntotal == 0:
212
+ return jsonify({'error': 'No documents uploaded yet. Please upload notes first.'}), 400
213
+
214
+ try:
215
+ # Retrieve relevant chunks
216
+ relevant_chunks = retrieve_relevant_chunks(question, top_k=5)
217
+
218
+ if not relevant_chunks:
219
+ return jsonify({'answer': 'No relevant information found in the uploaded notes.'}), 200
220
+
221
+ # Prepare context
222
+ context = "\n\n".join([chunk['text'] for chunk in relevant_chunks])
223
+ sources = list(set([chunk['filename'] for chunk in relevant_chunks]))
224
+
225
+ # Create prompt
226
+ prompt = f"""You are a helpful study assistant. Answer the question based ONLY on the provided context from the student's notes.
227
+
228
+ Context from notes:
229
+ {context}
230
+
231
+ Question: {question}
232
+
233
+ Instructions:
234
+ - Answer based ONLY on the context provided
235
+ - If the answer is not in the context, say "I cannot find this information in your uploaded notes"
236
+ - Be concise and clear
237
+ - Cite the relevant parts of the notes
238
+
239
+ Answer:"""
240
+
241
+ # Generate answer
242
+ answer = llm.invoke(prompt)
243
+
244
+ return jsonify({
245
+ 'answer': answer,
246
+ 'sources': sources,
247
+ 'relevant_chunks': len(relevant_chunks)
248
+ }), 200
249
+
250
+ except Exception as e:
251
+ return jsonify({'error': str(e)}), 500
252
+
253
+ @app.route('/summarize', methods=['POST'])
254
+ def summarize_notes():
255
+ """Summarize uploaded notes"""
256
+ data = request.get_json()
257
+ topic = data.get('topic', '')
258
+
259
+ if faiss_index.ntotal == 0:
260
+ return jsonify({'error': 'No documents uploaded yet. Please upload notes first.'}), 400
261
+
262
+ try:
263
+ # Retrieve relevant chunks
264
+ query = f"summary of {topic}" if topic else "all content"
265
+ relevant_chunks = retrieve_relevant_chunks(query, top_k=10)
266
+
267
+ if not relevant_chunks:
268
+ return jsonify({'error': 'No relevant information found'}), 400
269
+
270
+ # Prepare context
271
+ context = "\n\n".join([chunk['text'] for chunk in relevant_chunks])
272
+
273
+ # Create prompt
274
+ prompt = f"""Summarize the following notes into:
275
+ - Key points (bullet points)
276
+ - Short summary (5-6 lines)
277
+ - Definitions if present
278
+
279
+ Notes:
280
+ {context}
281
+
282
+ Provide a well-structured summary:"""
283
+
284
+ # Generate summary
285
+ summary = llm.invoke(prompt)
286
+
287
+ return jsonify({
288
+ 'summary': summary,
289
+ 'chunks_analyzed': len(relevant_chunks)
290
+ }), 200
291
+
292
+ except Exception as e:
293
+ return jsonify({'error': str(e)}), 500
294
+
295
+ @app.route('/generate-mcq', methods=['POST'])
296
+ def generate_mcq():
297
+ """Generate MCQs from uploaded notes"""
298
+ data = request.get_json()
299
+ topic = data.get('topic', '')
300
+ num_questions = data.get('num_questions', 5)
301
+
302
+ if faiss_index.ntotal == 0:
303
+ return jsonify({'error': 'No documents uploaded yet. Please upload notes first.'}), 400
304
+
305
+ try:
306
+ # Retrieve relevant chunks
307
+ query = f"questions about {topic}" if topic else "all content"
308
+ relevant_chunks = retrieve_relevant_chunks(query, top_k=10)
309
+
310
+ if not relevant_chunks:
311
+ return jsonify({'error': 'No relevant information found'}), 400
312
+
313
+ # Prepare context
314
+ context = "\n\n".join([chunk['text'] for chunk in relevant_chunks])
315
+
316
+ # Create prompt
317
+ prompt = f"""You are an MCQ generator. Using the provided context from notes, generate {num_questions} multiple choice questions (MCQs).
318
+
319
+ Context from notes:
320
+ {context}
321
+
322
+ For each MCQ, provide:
323
+ 1. Question
324
+ 2. Four options (A, B, C, D)
325
+ 3. Correct answer
326
+ 4. One-line explanation
327
+
328
+ Format each MCQ clearly with numbering.
329
+
330
+ Generate the MCQs:"""
331
+
332
+ # Generate MCQs
333
+ mcqs = llm.invoke(prompt)
334
+
335
+ return jsonify({
336
+ 'mcqs': mcqs,
337
+ 'chunks_used': len(relevant_chunks)
338
+ }), 200
339
+
340
+ except Exception as e:
341
+ return jsonify({'error': str(e)}), 500
342
+
343
+ @app.route('/stats', methods=['GET'])
344
+ def get_stats():
345
+ """Get system statistics"""
346
+ return jsonify({
347
+ 'total_vectors': faiss_index.ntotal,
348
+ 'total_documents': len(set([m['filename'] for m in metadata_store])) if metadata_store else 0,
349
+ 'total_chunks': len(metadata_store)
350
+ }), 200
351
+
352
+ # HTML Template
353
+ HTML_TEMPLATE = '''
354
+ <!DOCTYPE html>
355
+ <html lang="en">
356
+ <head>
357
+ <meta charset="UTF-8">
358
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
359
+ <title>Smart StudyMate - AI Study Assistant</title>
360
+ <style>
361
+ * {
362
+ margin: 0;
363
+ padding: 0;
364
+ box-sizing: border-box;
365
+ }
366
+
367
+ body {
368
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
369
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
370
+ min-height: 100vh;
371
+ padding: 20px;
372
+ }
373
+
374
+ .container {
375
+ max-width: 1200px;
376
+ margin: 0 auto;
377
+ background: white;
378
+ border-radius: 20px;
379
+ box-shadow: 0 20px 60px rgba(0,0,0,0.3);
380
+ overflow: hidden;
381
+ }
382
+
383
+ .header {
384
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
385
+ color: white;
386
+ padding: 30px;
387
+ text-align: center;
388
+ }
389
+
390
+ .header h1 {
391
+ font-size: 2.5em;
392
+ margin-bottom: 10px;
393
+ }
394
+
395
+ .header p {
396
+ font-size: 1.1em;
397
+ opacity: 0.9;
398
+ }
399
+
400
+ .stats {
401
+ display: flex;
402
+ justify-content: space-around;
403
+ background: #f8f9fa;
404
+ padding: 20px;
405
+ border-bottom: 2px solid #e9ecef;
406
+ }
407
+
408
+ .stat-item {
409
+ text-align: center;
410
+ }
411
+
412
+ .stat-value {
413
+ font-size: 2em;
414
+ font-weight: bold;
415
+ color: #667eea;
416
+ }
417
+
418
+ .stat-label {
419
+ color: #6c757d;
420
+ font-size: 0.9em;
421
+ margin-top: 5px;
422
+ }
423
+
424
+ .main-content {
425
+ display: grid;
426
+ grid-template-columns: 1fr 2fr;
427
+ gap: 20px;
428
+ padding: 30px;
429
+ }
430
+
431
+ .sidebar {
432
+ background: #f8f9fa;
433
+ padding: 20px;
434
+ border-radius: 10px;
435
+ }
436
+
437
+ .upload-section {
438
+ margin-bottom: 30px;
439
+ }
440
+
441
+ .upload-section h3 {
442
+ color: #333;
443
+ margin-bottom: 15px;
444
+ font-size: 1.2em;
445
+ }
446
+
447
+ .file-input-wrapper {
448
+ position: relative;
449
+ overflow: hidden;
450
+ display: inline-block;
451
+ width: 100%;
452
+ }
453
+
454
+ .file-input-wrapper input[type=file] {
455
+ position: absolute;
456
+ left: -9999px;
457
+ }
458
+
459
+ .file-input-label {
460
+ display: block;
461
+ padding: 15px;
462
+ background: #667eea;
463
+ color: white;
464
+ text-align: center;
465
+ border-radius: 8px;
466
+ cursor: pointer;
467
+ transition: background 0.3s;
468
+ }
469
+
470
+ .file-input-label:hover {
471
+ background: #5568d3;
472
+ }
473
+
474
+ .upload-btn {
475
+ width: 100%;
476
+ padding: 12px;
477
+ background: #28a745;
478
+ color: white;
479
+ border: none;
480
+ border-radius: 8px;
481
+ cursor: pointer;
482
+ font-size: 1em;
483
+ margin-top: 10px;
484
+ transition: background 0.3s;
485
+ }
486
+
487
+ .upload-btn:hover {
488
+ background: #218838;
489
+ }
490
+
491
+ .upload-btn:disabled {
492
+ background: #6c757d;
493
+ cursor: not-allowed;
494
+ }
495
+
496
+ .mode-selector {
497
+ margin-bottom: 20px;
498
+ }
499
+
500
+ .mode-btn {
501
+ width: 100%;
502
+ padding: 12px;
503
+ margin: 5px 0;
504
+ background: white;
505
+ border: 2px solid #667eea;
506
+ color: #667eea;
507
+ border-radius: 8px;
508
+ cursor: pointer;
509
+ font-size: 0.95em;
510
+ transition: all 0.3s;
511
+ }
512
+
513
+ .mode-btn:hover {
514
+ background: #f0f2ff;
515
+ }
516
+
517
+ .mode-btn.active {
518
+ background: #667eea;
519
+ color: white;
520
+ }
521
+
522
+ .chat-area {
523
+ display: flex;
524
+ flex-direction: column;
525
+ height: 600px;
526
+ }
527
+
528
+ .messages {
529
+ flex: 1;
530
+ overflow-y: auto;
531
+ padding: 20px;
532
+ background: #f8f9fa;
533
+ border-radius: 10px;
534
+ margin-bottom: 20px;
535
+ }
536
+
537
+ .message {
538
+ margin-bottom: 20px;
539
+ padding: 15px;
540
+ border-radius: 10px;
541
+ max-width: 80%;
542
+ animation: slideIn 0.3s;
543
+ }
544
+
545
+ @keyframes slideIn {
546
+ from {
547
+ opacity: 0;
548
+ transform: translateY(10px);
549
+ }
550
+ to {
551
+ opacity: 1;
552
+ transform: translateY(0);
553
+ }
554
+ }
555
+
556
+ .message.user {
557
+ background: #667eea;
558
+ color: white;
559
+ margin-left: auto;
560
+ }
561
+
562
+ .message.assistant {
563
+ background: white;
564
+ border: 1px solid #e9ecef;
565
+ }
566
+
567
+ .message.system {
568
+ background: #fff3cd;
569
+ border: 1px solid #ffeaa7;
570
+ color: #856404;
571
+ text-align: center;
572
+ margin: 10px auto;
573
+ max-width: 90%;
574
+ }
575
+
576
+ .message.error {
577
+ background: #f8d7da;
578
+ border: 1px solid #f5c6cb;
579
+ color: #721c24;
580
+ }
581
+
582
+ .input-area {
583
+ display: flex;
584
+ gap: 10px;
585
+ }
586
+
587
+ .input-area input {
588
+ flex: 1;
589
+ padding: 15px;
590
+ border: 2px solid #e9ecef;
591
+ border-radius: 10px;
592
+ font-size: 1em;
593
+ }
594
+
595
+ .input-area input:focus {
596
+ outline: none;
597
+ border-color: #667eea;
598
+ }
599
+
600
+ .send-btn {
601
+ padding: 15px 30px;
602
+ background: #667eea;
603
+ color: white;
604
+ border: none;
605
+ border-radius: 10px;
606
+ cursor: pointer;
607
+ font-size: 1em;
608
+ transition: background 0.3s;
609
+ }
610
+
611
+ .send-btn:hover {
612
+ background: #5568d3;
613
+ }
614
+
615
+ .send-btn:disabled {
616
+ background: #6c757d;
617
+ cursor: not-allowed;
618
+ }
619
+
620
+ .loading {
621
+ display: inline-block;
622
+ width: 20px;
623
+ height: 20px;
624
+ border: 3px solid #f3f3f3;
625
+ border-top: 3px solid #667eea;
626
+ border-radius: 50%;
627
+ animation: spin 1s linear infinite;
628
+ }
629
+
630
+ @keyframes spin {
631
+ 0% { transform: rotate(0deg); }
632
+ 100% { transform: rotate(360deg); }
633
+ }
634
+
635
+ .file-name {
636
+ margin-top: 10px;
637
+ padding: 10px;
638
+ background: white;
639
+ border-radius: 5px;
640
+ font-size: 0.9em;
641
+ color: #495057;
642
+ }
643
+
644
+ @media (max-width: 768px) {
645
+ .main-content {
646
+ grid-template-columns: 1fr;
647
+ }
648
+
649
+ .stats {
650
+ flex-direction: column;
651
+ gap: 15px;
652
+ }
653
+ }
654
+ </style>
655
+ </head>
656
+ <body>
657
+ <div class="container">
658
+ <div class="header">
659
+ <h1>πŸŽ“ Smart StudyMate</h1>
660
+ <p>Your AI-Powered Study Assistant with Local RAG</p>
661
+ </div>
662
+
663
+ <div class="stats">
664
+ <div class="stat-item">
665
+ <div class="stat-value" id="vectorCount">0</div>
666
+ <div class="stat-label">Vectors Stored</div>
667
+ </div>
668
+ <div class="stat-item">
669
+ <div class="stat-value" id="documentCount">0</div>
670
+ <div class="stat-label">Documents</div>
671
+ </div>
672
+ <div class="stat-item">
673
+ <div class="stat-value" id="chunkCount">0</div>
674
+ <div class="stat-label">Chunks</div>
675
+ </div>
676
+ </div>
677
+
678
+ <div class="main-content">
679
+ <div class="sidebar">
680
+ <div class="upload-section">
681
+ <h3>πŸ“€ Upload Notes</h3>
682
+ <div class="file-input-wrapper">
683
+ <input type="file" id="fileInput" accept=".pdf,.docx,.txt,.pptx">
684
+ <label for="fileInput" class="file-input-label">Choose File</label>
685
+ </div>
686
+ <div class="file-name" id="fileName">No file selected</div>
687
+ <button class="upload-btn" id="uploadBtn" disabled>Upload & Process</button>
688
+ </div>
689
+
690
+ <div class="mode-selector">
691
+ <h3>🎯 Mode</h3>
692
+ <button class="mode-btn active" data-mode="ask">πŸ’¬ Ask Questions</button>
693
+ <button class="mode-btn" data-mode="summarize">πŸ“ Summarize</button>
694
+ <button class="mode-btn" data-mode="mcq">❓ Generate MCQs</button>
695
+ </div>
696
+ </div>
697
+
698
+ <div class="chat-area">
699
+ <div class="messages" id="messages">
700
+ <div class="message system">
701
+ Welcome to Smart StudyMate! πŸ‘‹<br>
702
+ Upload your notes (PDF, DOCX, TXT, PPTX) to get started.
703
+ </div>
704
+ </div>
705
+
706
+ <div class="input-area">
707
+ <input type="text" id="userInput" placeholder="Ask a question about your notes...">
708
+ <button class="send-btn" id="sendBtn">Send</button>
709
+ </div>
710
+ </div>
711
+ </div>
712
+ </div>
713
+
714
+ <script>
715
+ let currentMode = 'ask';
716
+
717
+ // File upload handling
718
+ const fileInput = document.getElementById('fileInput');
719
+ const fileName = document.getElementById('fileName');
720
+ const uploadBtn = document.getElementById('uploadBtn');
721
+
722
+ fileInput.addEventListener('change', function() {
723
+ if (this.files.length > 0) {
724
+ fileName.textContent = this.files[0].name;
725
+ uploadBtn.disabled = false;
726
+ } else {
727
+ fileName.textContent = 'No file selected';
728
+ uploadBtn.disabled = true;
729
+ }
730
+ });
731
+
732
+ uploadBtn.addEventListener('click', async function() {
733
+ const file = fileInput.files[0];
734
+ if (!file) return;
735
+
736
+ const formData = new FormData();
737
+ formData.append('file', file);
738
+
739
+ uploadBtn.disabled = true;
740
+ uploadBtn.innerHTML = '<span class="loading"></span> Processing...';
741
+
742
+ try {
743
+ const response = await fetch('/upload', {
744
+ method: 'POST',
745
+ body: formData
746
+ });
747
+
748
+ const data = await response.json();
749
+
750
+ if (response.ok) {
751
+ addMessage('system', `βœ… ${data.message}<br>Created ${data.chunks_created} chunks. Total vectors: ${data.total_vectors}`);
752
+ updateStats();
753
+ fileInput.value = '';
754
+ fileName.textContent = 'No file selected';
755
+ } else {
756
+ addMessage('error', `❌ Error: ${data.error}`);
757
+ }
758
+ } catch (error) {
759
+ addMessage('error', `❌ Upload failed: ${error.message}`);
760
+ } finally {
761
+ uploadBtn.disabled = false;
762
+ uploadBtn.textContent = 'Upload & Process';
763
+ }
764
+ });
765
+
766
+ // Mode selection
767
+ document.querySelectorAll('.mode-btn').forEach(btn => {
768
+ btn.addEventListener('click', function() {
769
+ document.querySelectorAll('.mode-btn').forEach(b => b.classList.remove('active'));
770
+ this.classList.add('active');
771
+ currentMode = this.dataset.mode;
772
+
773
+ const input = document.getElementById('userInput');
774
+ if (currentMode === 'ask') {
775
+ input.placeholder = 'Ask a question about your notes...';
776
+ } else if (currentMode === 'summarize') {
777
+ input.placeholder = 'Enter topic to summarize (or leave empty for all)...';
778
+ } else if (currentMode === 'mcq') {
779
+ input.placeholder = 'Enter topic for MCQs (or leave empty for all)...';
780
+ }
781
+ });
782
+ });
783
+
784
+ // Chat handling
785
+ const userInput = document.getElementById('userInput');
786
+ const sendBtn = document.getElementById('sendBtn');
787
+ const messagesDiv = document.getElementById('messages');
788
+
789
+ async function sendMessage() {
790
+ const message = userInput.value.trim();
791
+ if (!message && currentMode === 'ask') return;
792
+
793
+ if (currentMode === 'ask') {
794
+ addMessage('user', message);
795
+ }
796
+
797
+ userInput.value = '';
798
+ sendBtn.disabled = true;
799
+
800
+ try {
801
+ let endpoint, body;
802
+
803
+ if (currentMode === 'ask') {
804
+ endpoint = '/ask';
805
+ body = { question: message };
806
+ } else if (currentMode === 'summarize') {
807
+ endpoint = '/summarize';
808
+ body = { topic: message };
809
+ addMessage('user', `Summarize: ${message || 'all notes'}`);
810
+ } else if (currentMode === 'mcq') {
811
+ endpoint = '/generate-mcq';
812
+ body = { topic: message, num_questions: 5 };
813
+ addMessage('user', `Generate MCQs: ${message || 'all notes'}`);
814
+ }
815
+
816
+ addMessage('assistant', '<span class="loading"></span> Thinking...');
817
+
818
+ const response = await fetch(endpoint, {
819
+ method: 'POST',
820
+ headers: { 'Content-Type': 'application/json' },
821
+ body: JSON.stringify(body)
822
+ });
823
+
824
+ const data = await response.json();
825
+
826
+ // Remove loading message
827
+ messagesDiv.lastChild.remove();
828
+
829
+ if (response.ok) {
830
+ if (currentMode === 'ask') {
831
+ addMessage('assistant', `${data.answer}<br><br><small>πŸ“š Sources: ${data.sources.join(', ')}</small>`);
832
+ } else if (currentMode === 'summarize') {
833
+ addMessage('assistant', data.summary.replace(/\n/g, '<br>'));
834
+ } else if (currentMode === 'mcq') {
835
+ addMessage('assistant', data.mcqs.replace(/\n/g, '<br>'));
836
+ }
837
+ } else {
838
+ addMessage('error', `❌ ${data.error}`);
839
+ }
840
+ } catch (error) {
841
+ messagesDiv.lastChild.remove();
842
+ addMessage('error', `❌ Error: ${error.message}`);
843
+ } finally {
844
+ sendBtn.disabled = false;
845
+ }
846
+ }
847
+
848
+ sendBtn.addEventListener('click', sendMessage);
849
+ userInput.addEventListener('keypress', function(e) {
850
+ if (e.key === 'Enter') sendMessage();
851
+ });
852
+
853
+ function addMessage(type, content) {
854
+ const messageDiv = document.createElement('div');
855
+ messageDiv.className = `message ${type}`;
856
+ messageDiv.innerHTML = content;
857
+ messagesDiv.appendChild(messageDiv);
858
+ messagesDiv.scrollTop = messagesDiv.scrollHeight;
859
+ }
860
+
861
+ async function updateStats() {
862
+ try {
863
+ const response = await fetch('/stats');
864
+ const data = await response.json();
865
+ document.getElementById('vectorCount').textContent = data.total_vectors;
866
+ document.getElementById('documentCount').textContent = data.total_documents;
867
+ document.getElementById('chunkCount').textContent = data.total_chunks;
868
+ } catch (error) {
869
+ console.error('Failed to update stats:', error);
870
+ }
871
+ }
872
+
873
+ // Initial stats load
874
+ updateStats();
875
+ </script>
876
+ </body>
877
+ </html>
878
+ '''
879
+
880
+ # Load FAISS index on startup
881
+ load_faiss_index()
882
+
883
+ if __name__ == '__main__':
884
+ print("\n" + "="*60)
885
+ print("πŸŽ“ Smart StudyMate - AI Study Assistant")
886
+ print("="*60)
887
+ print("\nStarting server...")
888
+ print("πŸ“Œ Access the application at: http://localhost:5000")
889
+ print("\n⚠️ Make sure Ollama is running with LLaMA 3.1 8B model!")
890
+ print(" Run: ollama pull llama3.1:8b")
891
+ print("="*60 + "\n")
892
+
893
+ app.run(debug=True, host='0.0.0.0', port=5000)