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 = '''
Your AI-Powered Study Assistant with Local RAG