File size: 7,613 Bytes
1703dbf
 
 
 
 
 
 
 
 
 
 
abafdc5
1703dbf
da06a8d
1703dbf
da06a8d
1703dbf
da06a8d
 
 
 
 
 
1703dbf
abafdc5
1703dbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abafdc5
 
7be3d03
1703dbf
 
 
 
abafdc5
7be3d03
abafdc5
7be3d03
 
 
1703dbf
da06a8d
 
7164f39
 
 
 
 
 
 
 
 
 
 
 
 
 
20ffede
7164f39
 
abafdc5
7164f39
 
 
 
 
 
 
 
 
 
 
20ffede
7164f39
 
 
 
 
20ffede
 
 
 
 
 
da06a8d
 
38b440f
da06a8d
 
7164f39
abafdc5
7164f39
 
 
 
 
 
 
 
20ffede
7164f39
 
 
 
 
20ffede
 
 
 
 
 
38b440f
da06a8d
38b440f
da06a8d
38b440f
 
abafdc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7164f39
1703dbf
abafdc5
da06a8d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
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("""<div id='header-text'><h1>RAG Bot with LlamaIndex (PDF + TXT)</h1></div>""")

        with gr.Tabs():
            # βœ… Tab 1: Paul Graham
            with gr.Tab("Paul Graham"):
                if os.path.exists("data/logo.png"):
                    gr.Image("data/logo.png", show_label=False, container=False, height=120)

                gr.Markdown("""
                    <div id='header-text'>
                        <h2>Paul Graham: Writing and Thinking</h2>
                        <p>Select a question or ask your own based on the essay.</p>
                    </div>
                """)

                dropdown_pg = gr.Dropdown(label="Pick a Question", choices=[""] + paul_questions, interactive=True)
                textbox_pg = gr.Textbox(label="Ask Anything", placeholder="Type your question...", lines=2)
                output_pg = gr.Textbox(label="Response", lines=10)
                submit_pg = gr.Button("Submit")
                clear_pg = gr.Button("Clear")

                def handle_pg_submit(drop_value, text_value):
                    final_query = drop_value if drop_value else text_value
                    if not final_query.strip():
                        return "❌ Please select or enter a question."
                    return query_pg(final_query)

                def handle_pg_clear():
                    return "", "", ""

                submit_pg.click(handle_pg_submit, inputs=[dropdown_pg, textbox_pg], outputs=output_pg)
                clear_pg.click(fn=handle_pg_clear, outputs=[dropdown_pg, textbox_pg, output_pg])

            # βœ… Tab 2: Insurance
            with gr.Tab("Insurance"):
                gr.Markdown("""
                    <div id='header-text'>
                        <h2>Understanding Insurance</h2>
                        <p>Explore key insurance concepts or ask your own questions.</p>
                    </div>
                """)

                dropdown_ins = gr.Dropdown(label="Pick a Question", choices=[""] + insurance_questions, interactive=True)
                textbox_ins = gr.Textbox(label="Ask Anything", placeholder="Type your question...", lines=2)
                output_ins = gr.Textbox(label="Response", lines=10)
                submit_ins = gr.Button("Submit")
                clear_ins = gr.Button("Clear")

                def handle_ins_submit(drop_value, text_value):
                    final_query = drop_value if drop_value else text_value
                    if not final_query.strip():
                        return "❌ Please select or enter a question."
                    return query_ins(final_query)

                def handle_ins_clear():
                    return "", "", ""

                submit_ins.click(handle_ins_submit, inputs=[dropdown_ins, textbox_ins], outputs=output_ins)
                clear_ins.click(fn=handle_ins_clear, outputs=[dropdown_ins, textbox_ins, output_ins])

            # βœ… Tab 3: Upload & Ask
            with gr.Tab("Upload & Ask"):
                gr.Markdown("""
                    <div id='header-text'>
                        <h2>Upload Your Document and Ask Questions</h2>
                        <p>Supported formats: PDF, TXT</p>
                    </div>
                """)

                upload_input = gr.File(label="Upload a document", file_types=[".pdf", ".txt"])
                user_question = gr.Textbox(label="Ask a question", placeholder="Type your question here", lines=2)
                upload_output = gr.Textbox(label="Response", lines=10)
                upload_submit = gr.Button("Submit")
                upload_clear = gr.Button("Clear")

                def handle_upload_question(file, query):
                    if not file or not query.strip():
                        return "❌ Please upload a file and enter a valid question."
                    try:
                        reader = SimpleDirectoryReader(input_files=[file.name])
                        docs = reader.load_data()
                        temp_index = VectorStoreIndex.from_documents(docs)
                        temp_engine = temp_index.as_query_engine()
                        return str(temp_engine.query(query))
                    except Exception as e:
                        return f"❌ Error: {str(e)}"

                def handle_upload_clear():
                    return None, "", ""

                upload_submit.click(fn=handle_upload_question, inputs=[upload_input, user_question], outputs=upload_output)
                upload_clear.click(fn=handle_upload_clear, outputs=[upload_input, user_question, upload_output])

    demo.launch()

# βœ… Launch app
launch_interface()