import os from pdf_parser import extract_text_from_pdf from rag import RAG from llm import ask_llm from utils import save_uploaded_file, cleanup_temp_files rag = RAG() def upload_document(file): if file is None: return "⚠️ Please select a valid PDF document.", "No document indexed." # 1. Save uploaded file to temp/ temp_path = save_uploaded_file(file) if not temp_path or not os.path.exists(temp_path): return "❌ Error saving uploaded file.", "Upload failed." try: # 2. Extract text from PDF text = extract_text_from_pdf(temp_path) if not text or not text.strip(): return "⚠️ No readable text found in PDF.", "Extraction empty." # 3. Create FAISS vector index rag.create_index(text) chunk_count = len(rag.chunks) filename = os.path.basename(temp_path) return ( f"✅ **{filename}** indexed successfully ({chunk_count} text chunks ready).", f"📄 Active: **{filename}** ({chunk_count} chunks)" ) finally: # 4. Clean up temporary folder cleanup_temp_files() def chat(question, history): if history is None: history = [] if not question or not question.strip(): return history results = rag.search(question) answer = ask_llm(results, question, history=history) # Gradio 6 chatbot messages format history.append({"role": "user", "content": question}) history.append({"role": "assistant", "content": answer}) return history def clear_chat(): return []