import os import gradio as gr from pathlib import Path from llama_index.core import SimpleDirectoryReader, VectorStoreIndex # Ensure data directory exists Path("data").mkdir(exist_ok=True) # Set OpenAI API key os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY") # Global state for engines state = {"insurance_engine": None, "paul_engine": None, "custom_engine": None} # Build index from file def build_index_from_file(file_path): documents = SimpleDirectoryReader(input_files=[file_path]).load_data() index = VectorStoreIndex.from_documents(documents) return index.as_query_engine() # Preload fixed documents def preload_indexes(): try: state["insurance_engine"] = build_index_from_file("data/insurance_FirstRAG.pdf") except: print("❌ Failed to load insurance.pdf") try: state["paul_engine"] = build_index_from_file("data/paul_graham_FirstRAG.txt") except: print("❌ Failed to load paul_graham.txt") # Upload custom file def upload_and_refresh(file_path): if file_path is None: return "⚠️ No file uploaded." try: state["custom_engine"] = build_index_from_file(file_path) return f"✅ Uploaded & Indexed: {os.path.basename(file_path)}" except Exception as e: return f"❌ Failed: {str(e)}" # Query helpers def ask_insurance(query): return _query_engine(state["insurance_engine"], query) def ask_paul(query): return _query_engine(state["paul_engine"], query) def ask_custom(query): return _query_engine(state["custom_engine"], query) def _query_engine(engine, query): if not query: return "❗ Please enter a question." if engine is None: return "📂 Document not loaded yet." try: return str(engine.query(query)) except Exception as e: return f"❌ Error: {str(e)}" # Summarize def summarize_insurance(): return _query_engine(state["insurance_engine"], "Summarize the insurance document.") def summarize_paul(): return _query_engine(state["paul_engine"], "Summarize Paul Graham's main ideas.") def summarize_custom(): return _query_engine(state["custom_engine"], "Summarize the uploaded documents.") # Clear def clear_fields(): return "", "" # Launch app def launch(): preload_indexes() with gr.Blocks( title="RAG App with LlamaIndex", css=""" body { background-color: #f5f5dc; font-family: 'Georgia', 'Merriweather', serif; } h1 { font-size: 2.5em; font-weight: bold; color: #4e342e; margin-bottom: 0.3em; } .subtitle { font-size: 1.2em; color: #6d4c41; margin-bottom: 1.5em; } .gr-box, .gr-column, .gr-group { border-radius: 15px; padding: 20px; background-color: #fffaf0; box-shadow: 2px 4px 14px rgba(0, 0, 0, 0.1); margin-top: 10px; } textarea, input[type="text"], input[type="file"] { background-color: #fffaf0; border: 1px solid #d2b48c; color: #4e342e; border-radius: 8px; } button { background-color: #a1887f; color: white; font-weight: bold; border-radius: 8px; transition: background-color 0.3s ease; } button:hover { background-color: #8d6e63; } .gr-button { border-radius: 8px !important; } .tabitem { border-radius: 15px !important; } """ ) as app: with gr.Column(): gr.Markdown("""