File size: 28,261 Bytes
3beb728 | 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 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 | from flask import Flask, request, jsonify, render_template_string
from werkzeug.utils import secure_filename
import os
import PyPDF2
import docx
from pptx import Presentation
from sentence_transformers import SentenceTransformer
import faiss
import numpy as np
import pickle
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.llms import Ollama
import json
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 # 50MB max file size
app.config['FAISS_INDEX_PATH'] = 'faiss_index'
app.config['METADATA_PATH'] = 'metadata.pkl'
# Create necessary directories
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs(app.config['FAISS_INDEX_PATH'], exist_ok=True)
# Initialize models
print("Loading Sentence Transformer model...")
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
print("Initializing Ollama LLaMA 3.1...")
llm = Ollama(model="llama3.1:8b", temperature=0.3)
# Global variables for FAISS index
faiss_index = None
metadata_store = []
dimension = 384 # all-MiniLM-L6-v2 embedding dimension
def load_faiss_index():
"""Load existing FAISS index and metadata"""
global faiss_index, metadata_store
index_path = os.path.join(app.config['FAISS_INDEX_PATH'], 'index.faiss')
metadata_path = os.path.join(app.config['FAISS_INDEX_PATH'], app.config['METADATA_PATH'])
if os.path.exists(index_path) and os.path.exists(metadata_path):
faiss_index = faiss.read_index(index_path)
with open(metadata_path, 'rb') as f:
metadata_store = pickle.load(f)
print(f"Loaded FAISS index with {faiss_index.ntotal} vectors")
else:
faiss_index = faiss.IndexFlatL2(dimension)
metadata_store = []
print("Created new FAISS index")
def save_faiss_index():
"""Save FAISS index and metadata persistently"""
index_path = os.path.join(app.config['FAISS_INDEX_PATH'], 'index.faiss')
metadata_path = os.path.join(app.config['FAISS_INDEX_PATH'], app.config['METADATA_PATH'])
faiss.write_index(faiss_index, index_path)
with open(metadata_path, 'wb') as f:
pickle.dump(metadata_store, f)
print(f"Saved FAISS index with {faiss_index.ntotal} vectors")
def extract_text_from_pdf(file_path):
"""Extract text from PDF files"""
text = ""
with open(file_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
for page in pdf_reader.pages:
text += page.extract_text() + "\n"
return text
def extract_text_from_docx(file_path):
"""Extract text from DOCX files"""
doc = docx.Document(file_path)
text = "\n".join([paragraph.text for paragraph in doc.paragraphs])
return text
def extract_text_from_txt(file_path):
"""Extract text from TXT files"""
with open(file_path, 'r', encoding='utf-8', errors='ignore') as file:
text = file.read()
return text
def extract_text_from_pptx(file_path):
"""Extract text from PPTX files"""
prs = Presentation(file_path)
text = ""
for slide in prs.slides:
for shape in slide.shapes:
if hasattr(shape, "text"):
text += shape.text + "\n"
return text
def extract_text(file_path, file_extension):
"""Extract text based on file type"""
if file_extension == '.pdf':
return extract_text_from_pdf(file_path)
elif file_extension == '.docx':
return extract_text_from_docx(file_path)
elif file_extension == '.txt':
return extract_text_from_txt(file_path)
elif file_extension == '.pptx':
return extract_text_from_pptx(file_path)
else:
raise ValueError(f"Unsupported file type: {file_extension}")
def chunk_text(text, chunk_size=500):
"""Split text into chunks using RecursiveCharacterTextSplitter"""
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size,
chunk_overlap=50,
length_function=len,
)
chunks = text_splitter.split_text(text)
return chunks
def add_to_faiss(chunks, filename):
"""Add chunks to FAISS index with metadata"""
global faiss_index, metadata_store
embeddings = embedding_model.encode(chunks, show_progress_bar=True)
embeddings = np.array(embeddings).astype('float32')
# Add to FAISS index
faiss_index.add(embeddings)
# Store metadata
for i, chunk in enumerate(chunks):
metadata_store.append({
'filename': filename,
'chunk_id': len(metadata_store),
'text': chunk
})
save_faiss_index()
def retrieve_relevant_chunks(query, top_k=5):
"""Retrieve top-k relevant chunks from FAISS"""
if faiss_index.ntotal == 0:
return []
query_embedding = embedding_model.encode([query])
query_embedding = np.array(query_embedding).astype('float32')
distances, indices = faiss_index.search(query_embedding, min(top_k, faiss_index.ntotal))
results = []
for idx in indices[0]:
if idx < len(metadata_store):
results.append(metadata_store[idx])
return results
@app.route('/')
def index():
"""Render the main chat interface"""
return render_template_string(HTML_TEMPLATE)
@app.route('/upload', methods=['POST'])
def upload_file():
"""Upload and process files"""
if 'file' not in request.files:
return jsonify({'error': 'No file provided'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No file selected'}), 400
filename = secure_filename(file.filename)
file_extension = os.path.splitext(filename)[1].lower()
if file_extension not in ['.pdf', '.docx', '.txt', '.pptx']:
return jsonify({'error': 'Unsupported file type. Please upload PDF, DOCX, TXT, or PPTX'}), 400
try:
# Save file
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(file_path)
# Extract text
text = extract_text(file_path, file_extension)
if not text.strip():
return jsonify({'error': 'No text could be extracted from the file'}), 400
# Chunk text
chunks = chunk_text(text)
# Add to FAISS
add_to_faiss(chunks, filename)
return jsonify({
'message': f'Successfully uploaded and processed {filename}',
'chunks_created': len(chunks),
'total_vectors': faiss_index.ntotal
}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/ask', methods=['POST'])
def ask_question():
"""Answer questions based on uploaded notes"""
data = request.get_json()
question = data.get('question', '')
if not question:
return jsonify({'error': 'No question provided'}), 400
if faiss_index.ntotal == 0:
return jsonify({'error': 'No documents uploaded yet. Please upload notes first.'}), 400
try:
# Retrieve relevant chunks
relevant_chunks = retrieve_relevant_chunks(question, top_k=5)
if not relevant_chunks:
return jsonify({'answer': 'No relevant information found in the uploaded notes.'}), 200
# Prepare context
context = "\n\n".join([chunk['text'] for chunk in relevant_chunks])
sources = list(set([chunk['filename'] for chunk in relevant_chunks]))
# Create prompt
prompt = f"""You are a helpful study assistant. Answer the question based ONLY on the provided context from the student's notes.
Context from notes:
{context}
Question: {question}
Instructions:
- Answer based ONLY on the context provided
- If the answer is not in the context, say "I cannot find this information in your uploaded notes"
- Be concise and clear
- Cite the relevant parts of the notes
Answer:"""
# Generate answer
answer = llm.invoke(prompt)
return jsonify({
'answer': answer,
'sources': sources,
'relevant_chunks': len(relevant_chunks)
}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/summarize', methods=['POST'])
def summarize_notes():
"""Summarize uploaded notes"""
data = request.get_json()
topic = data.get('topic', '')
if faiss_index.ntotal == 0:
return jsonify({'error': 'No documents uploaded yet. Please upload notes first.'}), 400
try:
# Retrieve relevant chunks
query = f"summary of {topic}" if topic else "all content"
relevant_chunks = retrieve_relevant_chunks(query, top_k=10)
if not relevant_chunks:
return jsonify({'error': 'No relevant information found'}), 400
# Prepare context
context = "\n\n".join([chunk['text'] for chunk in relevant_chunks])
# Create prompt
prompt = f"""Summarize the following notes into:
- Key points (bullet points)
- Short summary (5-6 lines)
- Definitions if present
Notes:
{context}
Provide a well-structured summary:"""
# Generate summary
summary = llm.invoke(prompt)
return jsonify({
'summary': summary,
'chunks_analyzed': len(relevant_chunks)
}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/generate-mcq', methods=['POST'])
def generate_mcq():
"""Generate MCQs from uploaded notes"""
data = request.get_json()
topic = data.get('topic', '')
num_questions = data.get('num_questions', 5)
if faiss_index.ntotal == 0:
return jsonify({'error': 'No documents uploaded yet. Please upload notes first.'}), 400
try:
# Retrieve relevant chunks
query = f"questions about {topic}" if topic else "all content"
relevant_chunks = retrieve_relevant_chunks(query, top_k=10)
if not relevant_chunks:
return jsonify({'error': 'No relevant information found'}), 400
# Prepare context
context = "\n\n".join([chunk['text'] for chunk in relevant_chunks])
# Create prompt
prompt = f"""You are an MCQ generator. Using the provided context from notes, generate {num_questions} multiple choice questions (MCQs).
Context from notes:
{context}
For each MCQ, provide:
1. Question
2. Four options (A, B, C, D)
3. Correct answer
4. One-line explanation
Format each MCQ clearly with numbering.
Generate the MCQs:"""
# Generate MCQs
mcqs = llm.invoke(prompt)
return jsonify({
'mcqs': mcqs,
'chunks_used': len(relevant_chunks)
}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/stats', methods=['GET'])
def get_stats():
"""Get system statistics"""
return jsonify({
'total_vectors': faiss_index.ntotal,
'total_documents': len(set([m['filename'] for m in metadata_store])) if metadata_store else 0,
'total_chunks': len(metadata_store)
}), 200
# HTML Template
HTML_TEMPLATE = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Smart StudyMate - AI Study Assistant</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 1200px;
margin: 0 auto;
background: white;
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
text-align: center;
}
.header h1 {
font-size: 2.5em;
margin-bottom: 10px;
}
.header p {
font-size: 1.1em;
opacity: 0.9;
}
.stats {
display: flex;
justify-content: space-around;
background: #f8f9fa;
padding: 20px;
border-bottom: 2px solid #e9ecef;
}
.stat-item {
text-align: center;
}
.stat-value {
font-size: 2em;
font-weight: bold;
color: #667eea;
}
.stat-label {
color: #6c757d;
font-size: 0.9em;
margin-top: 5px;
}
.main-content {
display: grid;
grid-template-columns: 1fr 2fr;
gap: 20px;
padding: 30px;
}
.sidebar {
background: #f8f9fa;
padding: 20px;
border-radius: 10px;
}
.upload-section {
margin-bottom: 30px;
}
.upload-section h3 {
color: #333;
margin-bottom: 15px;
font-size: 1.2em;
}
.file-input-wrapper {
position: relative;
overflow: hidden;
display: inline-block;
width: 100%;
}
.file-input-wrapper input[type=file] {
position: absolute;
left: -9999px;
}
.file-input-label {
display: block;
padding: 15px;
background: #667eea;
color: white;
text-align: center;
border-radius: 8px;
cursor: pointer;
transition: background 0.3s;
}
.file-input-label:hover {
background: #5568d3;
}
.upload-btn {
width: 100%;
padding: 12px;
background: #28a745;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
font-size: 1em;
margin-top: 10px;
transition: background 0.3s;
}
.upload-btn:hover {
background: #218838;
}
.upload-btn:disabled {
background: #6c757d;
cursor: not-allowed;
}
.mode-selector {
margin-bottom: 20px;
}
.mode-btn {
width: 100%;
padding: 12px;
margin: 5px 0;
background: white;
border: 2px solid #667eea;
color: #667eea;
border-radius: 8px;
cursor: pointer;
font-size: 0.95em;
transition: all 0.3s;
}
.mode-btn:hover {
background: #f0f2ff;
}
.mode-btn.active {
background: #667eea;
color: white;
}
.chat-area {
display: flex;
flex-direction: column;
height: 600px;
}
.messages {
flex: 1;
overflow-y: auto;
padding: 20px;
background: #f8f9fa;
border-radius: 10px;
margin-bottom: 20px;
}
.message {
margin-bottom: 20px;
padding: 15px;
border-radius: 10px;
max-width: 80%;
animation: slideIn 0.3s;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.message.user {
background: #667eea;
color: white;
margin-left: auto;
}
.message.assistant {
background: white;
border: 1px solid #e9ecef;
}
.message.system {
background: #fff3cd;
border: 1px solid #ffeaa7;
color: #856404;
text-align: center;
margin: 10px auto;
max-width: 90%;
}
.message.error {
background: #f8d7da;
border: 1px solid #f5c6cb;
color: #721c24;
}
.input-area {
display: flex;
gap: 10px;
}
.input-area input {
flex: 1;
padding: 15px;
border: 2px solid #e9ecef;
border-radius: 10px;
font-size: 1em;
}
.input-area input:focus {
outline: none;
border-color: #667eea;
}
.send-btn {
padding: 15px 30px;
background: #667eea;
color: white;
border: none;
border-radius: 10px;
cursor: pointer;
font-size: 1em;
transition: background 0.3s;
}
.send-btn:hover {
background: #5568d3;
}
.send-btn:disabled {
background: #6c757d;
cursor: not-allowed;
}
.loading {
display: inline-block;
width: 20px;
height: 20px;
border: 3px solid #f3f3f3;
border-top: 3px solid #667eea;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.file-name {
margin-top: 10px;
padding: 10px;
background: white;
border-radius: 5px;
font-size: 0.9em;
color: #495057;
}
@media (max-width: 768px) {
.main-content {
grid-template-columns: 1fr;
}
.stats {
flex-direction: column;
gap: 15px;
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>π Smart StudyMate</h1>
<p>Your AI-Powered Study Assistant with Local RAG</p>
</div>
<div class="stats">
<div class="stat-item">
<div class="stat-value" id="vectorCount">0</div>
<div class="stat-label">Vectors Stored</div>
</div>
<div class="stat-item">
<div class="stat-value" id="documentCount">0</div>
<div class="stat-label">Documents</div>
</div>
<div class="stat-item">
<div class="stat-value" id="chunkCount">0</div>
<div class="stat-label">Chunks</div>
</div>
</div>
<div class="main-content">
<div class="sidebar">
<div class="upload-section">
<h3>π€ Upload Notes</h3>
<div class="file-input-wrapper">
<input type="file" id="fileInput" accept=".pdf,.docx,.txt,.pptx">
<label for="fileInput" class="file-input-label">Choose File</label>
</div>
<div class="file-name" id="fileName">No file selected</div>
<button class="upload-btn" id="uploadBtn" disabled>Upload & Process</button>
</div>
<div class="mode-selector">
<h3>π― Mode</h3>
<button class="mode-btn active" data-mode="ask">π¬ Ask Questions</button>
<button class="mode-btn" data-mode="summarize">π Summarize</button>
<button class="mode-btn" data-mode="mcq">β Generate MCQs</button>
</div>
</div>
<div class="chat-area">
<div class="messages" id="messages">
<div class="message system">
Welcome to Smart StudyMate! π<br>
Upload your notes (PDF, DOCX, TXT, PPTX) to get started.
</div>
</div>
<div class="input-area">
<input type="text" id="userInput" placeholder="Ask a question about your notes...">
<button class="send-btn" id="sendBtn">Send</button>
</div>
</div>
</div>
</div>
<script>
let currentMode = 'ask';
// File upload handling
const fileInput = document.getElementById('fileInput');
const fileName = document.getElementById('fileName');
const uploadBtn = document.getElementById('uploadBtn');
fileInput.addEventListener('change', function() {
if (this.files.length > 0) {
fileName.textContent = this.files[0].name;
uploadBtn.disabled = false;
} else {
fileName.textContent = 'No file selected';
uploadBtn.disabled = true;
}
});
uploadBtn.addEventListener('click', async function() {
const file = fileInput.files[0];
if (!file) return;
const formData = new FormData();
formData.append('file', file);
uploadBtn.disabled = true;
uploadBtn.innerHTML = '<span class="loading"> Processing...';
try {
const response = await fetch('/upload', {
method: 'POST',
body: formData
});
const data = await response.json();
if (response.ok) {
addMessage('system', `β
${data.message}Created ${data.chunks_created} chunks. Total vectors: ${data.total_vectors}`);
updateStats();
fileInput.value = '';
fileName.textContent = 'No file selected';
} else {
addMessage('error', `β Error: ${data.error}`);
}
} catch (error) {
addMessage('error', `β Upload failed: ${error.message}`);
} finally {
uploadBtn.disabled = false;
uploadBtn.textContent = 'Upload & Process';
}
});
// Mode selection
document.querySelectorAll('.mode-btn').forEach(btn => {
btn.addEventListener('click', function() {
document.querySelectorAll('.mode-btn').forEach(b => b.classList.remove('active'));
this.classList.add('active');
currentMode = this.dataset.mode;
const input = document.getElementById('userInput');
if (currentMode === 'ask') {
input.placeholder = 'Ask a question about your notes...';
} else if (currentMode === 'summarize') {
input.placeholder = 'Enter topic to summarize (or leave empty for all)...';
} else if (currentMode === 'mcq') {
input.placeholder = 'Enter topic for MCQs (or leave empty for all)...';
}
});
});
// Chat handling
const userInput = document.getElementById('userInput');
const sendBtn = document.getElementById('sendBtn');
const messagesDiv = document.getElementById('messages');
async function sendMessage() {
const message = userInput.value.trim();
if (!message && currentMode === 'ask') return;
if (currentMode === 'ask') {
addMessage('user', message);
}
userInput.value = '';
sendBtn.disabled = true;
try {
let endpoint, body;
if (currentMode === 'ask') {
endpoint = '/ask';
body = { question: message };
} else if (currentMode === 'summarize') {
endpoint = '/summarize';
body = { topic: message };
addMessage('user', `Summarize: ${message || 'all notes'}`);
} else if (currentMode === 'mcq') {
endpoint = '/generate-mcq';
body = { topic: message, num_questions: 5 };
addMessage('user', `Generate MCQs: ${message || 'all notes'}`);
}
addMessage('assistant', '<span class="loading"></span> Thinking...');
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
const data = await response.json();
// Remove loading message
messagesDiv.lastChild.remove();
if (response.ok) {
if (currentMode === 'ask') {
addMessage('assistant', `${data.answer}<br><br><small>π Sources: ${data.sources.join(', ')}</small>`);
} else if (currentMode === 'summarize') {
addMessage('assistant', data.summary.replace(/\n/g, '<br>'));
} else if (currentMode === 'mcq') {
addMessage('assistant', data.mcqs.replace(/\n/g, '<br>'));
}
} else {
addMessage('error', `β ${data.error}`);
}
} catch (error) {
messagesDiv.lastChild.remove();
addMessage('error', `β Error: ${error.message}`);
} finally {
sendBtn.disabled = false;
}
}
sendBtn.addEventListener('click', sendMessage);
userInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') sendMessage();
});
function addMessage(type, content) {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${type}`;
messageDiv.innerHTML = content;
messagesDiv.appendChild(messageDiv);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
async function updateStats() {
try {
const response = await fetch('/stats');
const data = await response.json();
document.getElementById('vectorCount').textContent = data.total_vectors;
document.getElementById('documentCount').textContent = data.total_documents;
document.getElementById('chunkCount').textContent = data.total_chunks;
} catch (error) {
console.error('Failed to update stats:', error);
}
}
// Initial stats load
updateStats();
</script>
</body>
</html>
'''
# Load FAISS index on startup
load_faiss_index()
if __name__ == '__main__':
print("\n" + "="*60)
print("π Smart StudyMate - AI Study Assistant")
print("="*60)
print("\nStarting server...")
print("π Access the application at: http://localhost:5000")
print("\nβ οΈ Make sure Ollama is running with LLaMA 3.1 8B model!")
print(" Run: ollama pull llama3.1:8b")
print("="*60 + "\n")
app.run(debug=True, host='0.0.0.0', port=5000) |