import gradio as gr import os from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings from llama_index.embeddings.huggingface import HuggingFaceEmbedding # ✅ Access OpenAI API Key openai_api_key = os.environ.get("OPENAI_API_KEY") if not openai_api_key: raise ValueError("❌ OPENAI_API_KEY not found. Add it in Space settings > Secrets.") os.environ["OPENAI_API_KEY"] = openai_api_key # ✅ Set Hugging Face Embedding globally embed_model = HuggingFaceEmbedding(model_name="sentence-transformers/all-MiniLM-L6-v2") Settings.embed_model = embed_model # ✅ Load and filter documents def load_filtered_docs(folder): try: docs = SimpleDirectoryReader(folder).load_data() return [doc for doc in docs if doc.text and doc.text.strip()] except Exception as e: print(f"❌ Error loading docs from {folder}: {e}") return [] # ✅ Load predefined document sets pg_docs = load_filtered_docs("data/paul") pg_index = VectorStoreIndex.from_documents(pg_docs) pg_engine = pg_index.as_query_engine() ins_docs = load_filtered_docs("data/insurance") ins_index = VectorStoreIndex.from_documents(ins_docs) ins_engine = ins_index.as_query_engine() # ✅ Query functions def query_pg(query): if not query.strip(): return "❌ Please enter a valid question before submitting." try: return str(pg_engine.query(query)) except Exception as e: return f"❌ Error: {str(e)}" def query_ins(query): if not query.strip(): return "❌ Please enter a valid question before submitting." try: return str(ins_engine.query(query)) except Exception as e: return f"❌ Error: {str(e)}" # ✅ Predefined questions paul_questions = [ "What is the main purpose of writing, according to Paul Graham?", "Why do students often struggle with writing in school?", "How does Paul Graham describe the relationship between writing and thinking?", "What is one reason Paul Graham gives for why school essays feel boring?", "What does Paul Graham suggest writers should focus on first?", "What is the link between curiosity and writing?", "How can one write more clearly according to Paul Graham?" ] insurance_questions = [ "What is insurance and why is it important?", "What should you check before buying insurance?", "What are the primary types of insurance?", "What is health insurance and what does it cover?", "How does life insurance differ from term insurance?", "What is the difference between premium and coverage?", "How is insurance regulated?" ] # ✅ Gradio interface def launch_interface(): with gr.Blocks( title="RAG App", css=""" .gradio-container { background-color: #e6fff7 !important; } #header-text { text-align: center; color: #2b6777; } """ ) as demo: gr.Markdown("""
Select a question or ask your own based on the essay.
Explore key insurance concepts or ask your own questions.
Supported formats: PDF, TXT