Update README.md
Browse files
README.md
CHANGED
|
@@ -1,395 +1,893 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
#
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
---
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
#
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
#
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
-
|
| 392 |
-
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|