README / app.py
Rsukesh001's picture
Upload app.py
272f1d4 verified
Raw History Blame Contribute Delete
29.2 kB
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_splitter 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"></span> Processing...';
try {
const response = await fetch('/upload', {
method: 'POST',
body: formData
});
const data = await response.json();
if (response.ok) {
addMessage('system', `βœ… ${data.message}<br>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)