File size: 8,780 Bytes
0628cbb
226da61
0628cbb
b971de8
5362520
0628cbb
b971de8
8dfb503
 
23daf07
 
 
 
8dfb503
 
 
 
23daf07
 
a248573
 
0795f5a
 
1ab74f5
b971de8
 
 
 
 
8bfb7cc
 
3cf3e00
 
35ffa2b
3cf3e00
 
8dfb503
35ffa2b
17d5dd8
35ffa2b
 
 
 
b971de8
35ffa2b
 
 
 
 
37b582d
 
 
 
 
 
176c1e8
 
37b582d
23daf07
35ffa2b
 
3cf3e00
35ffa2b
5362520
35ffa2b
5362520
35ffa2b
5362520
 
35ffa2b
 
 
 
 
 
 
 
 
 
5362520
17d5dd8
35ffa2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37b582d
 
 
 
 
35ffa2b
0795f5a
 
 
 
 
 
8bfb7cc
5362520
8bfb7cc
 
35ffa2b
 
b273adc
 
 
 
35ffa2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b971de8
 
 
8bfb7cc
b971de8
 
8bfb7cc
5d2245e
226da61
d2770d0
23daf07
226da61
7fd9f8f
 
8bfb7cc
8dfb503
4a84d58
a27634d
 
7fd9f8f
 
 
b971de8
7fd9f8f
23daf07
35ffa2b
 
 
 
 
 
 
9892ae2
35ffa2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b273adc
35ffa2b
 
37b582d
3cf3e00
b273adc
a248573
23daf07
37b582d
 
3cf3e00
a248573
 
35ffa2b
 
b273adc
ca9cc5e
b971de8
538e101
8bfb7cc
 
0628cbb
b971de8
17a737c
 
 
 
 
 
0795f5a
 
3cf3e00
0795f5a
b971de8
069e614
 
0795f5a
 
 
 
 
 
37b582d
0795f5a
 
 
 
 
069e614
 
 
 
 
0795f5a
069e614
 
0795f5a
 
17a737c
b971de8
17a737c
 
 
e36ffb0
17a737c
 
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import streamlit as st
import time

# FIRST: Set page config before ANY other Streamlit command
st.set_page_config(page_title="Spirituality Q&A")

# Initialize ALL session state variables right at the beginning
if 'initialized' not in st.session_state:
    st.session_state.initialized = False
if 'model' not in st.session_state:
    st.session_state.model = None
if 'tokenizer' not in st.session_state:
    st.session_state.tokenizer = None
if 'last_query' not in st.session_state:
    st.session_state.last_query = ""
if 'submit_clicked' not in st.session_state:
    st.session_state.submit_clicked = False
if 'init_time' not in st.session_state:
    st.session_state.init_time = None
if 'form_key' not in st.session_state:
    st.session_state.form_key = 0  # This will help us reset the form
if 'processing' not in st.session_state:
    st.session_state.processing = False

# THEN: Import your modules
from rag_engine import process_query, load_model
from utils import setup_all_auth

# Custom styling (pure CSS)
st.markdown("""
<style>
.main-title {
    font-size: 2.5rem;
    color: #c0392b;
    text-align: center;
    margin-bottom: 1rem;
}
/* Button styling */
.stButton>button {
    background-color: #fff0f0 !important;
    color: #3f51b5 !important;
    border: 1px solid #e1e4f2 !important;
    border-radius: 20px !important;
    padding: 8px 16px !important;
    box-shadow: 0 1px 2px rgba(0,0,0,0.03) !important;
    white-space: nowrap !important;
    overflow: hidden !important;
    text-overflow: ellipsis !important;
}
/* Form submit button specific styling */
button[type="submit"], 
.stFormSubmit>button, 
[data-testid="stFormSubmitButton"]>button {
    background-color: #fff0f0 !important;
    color: #3f51b5 !important;
    border: 1px solid #e1e4f2 !important;
    border-radius: 8px !important;
}
.stButton>button:hover {
    background-color: #fafbff !important;
    border-color: #c5cae9 !important;
}
/* Input field styling */
div[data-baseweb="input"] {
    border: 1px solid #fff0f0 !important;
    border-radius: 8px !important;
    background-color: #ffffff !important;
}
div[data-baseweb="input"]:focus-within {
    border: 1px solid #3f51b5 !important;
}
div[data-baseweb="input"]:active {
    border: 1px solid #fff0f0 !important;
}
/* Style the st.info boxes */
div.stInfo {
    background-color: #f8faff !important;
    color: #3f51b5 !important;
    border: 1px solid #e1e4f2 !important;
    border-radius: 8px !important;
}
/* COMBINED SCROLL CONTAINER */
.questions-scroll-container {
    width: 100%;
    overflow-x: auto;
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE and Edge */
}
/* Hide scrollbar for Chrome, Safari and Opera */
.questions-scroll-container::-webkit-scrollbar {
    display: none;
}
/* Inner content that holds both rows */
.questions-content {
    display: inline-flex;
    flex-direction: column;
    min-width: max-content;
    gap: 10px;
    padding: 5px 0;
}
/* Individual rows */
.questions-row {
    display: flex;
    flex-direction: row;
    gap: 10px;
}
/* Placeholder for buttons */
.button-placeholder {
    min-height: 38px;
    min-width: 120px;
    margin: 0 5px;
}
/* Hide "Press Enter to submit form" text */
.stTextInput label + div + div small,
[data-testid="stForm"] small,
form small {
    display: none !important;
}
</style>
<div class="main-title">Spirituality Q&A</div>
""", unsafe_allow_html=True)

# Function to handle query selection
def set_query(query):
    if not st.session_state.processing:
        st.session_state.last_query = query
        st.session_state.submit_clicked = True
        st.rerun()

# Function to group questions into rows based on length
def group_buttons(questions, max_chars_per_row=100):
    rows = []
    current_row = []
    current_length = 0
    
    for q in questions:
        # Add some buffer for button padding/margins
        q_length = len(q) + 5
        
        if current_length + q_length > max_chars_per_row and current_row:
            rows.append(current_row)
            current_row = [q]
            current_length = q_length
        else:
            current_row.append(q)
            current_length += q_length
    
    if current_row:
        rows.append(current_row)
    
    return rows

# Handle initialization and success message timing
init_message = st.empty()

if not st.session_state.initialized:
    init_message.info("Hang in there! We are setting the system up for you. 😊")

    try:
        setup_all_auth()
        load_model()
        st.session_state.initialized = True
        st.session_state.init_time = time.time()
        init_message.success("System initialized successfully!")
        time.sleep(2)
        init_message.empty()
    except Exception as e:
        init_message.error(f"Error initializing: {str(e)}")

# Handle timing of success message disappearance
# This will run on each rerender after initialization
elif st.session_state.init_time is not None:
    elapsed_time = time.time() - st.session_state.init_time
    if elapsed_time >= 2.0:
        init_message.empty()
        st.session_state.init_time = None

# All common questions in a single list
common_questions = [
    "What is the Atman or the soul?",
    "Are there rebirths?",
    "What is Karma?",
    "What is the ultimate truth?",
    "What is Swami Vivekananda's opinion about the SELF?",
    "Explain moksha or salvation. Is that for real?",
    "Destiny or free will?",
    "What is the ultimate goal of human life?",
    "Do we really die?",
    "How can you attain self-realization?"
]

# Display heading for common questions
st.markdown("### Common questions to try:")

# Group questions into rows
question_rows = group_buttons(common_questions, max_chars_per_row=80)

# Create buttons for each row
for row_idx, row in enumerate(question_rows):
    cols = st.columns(len(row))
    for i, (col, q) in enumerate(zip(cols, row)):
        with col:
            if st.button(q, key=f"r{row_idx}_q{i}", use_container_width=True, disabled=st.session_state.processing):
                set_query(q)

# Function to handle form submission
def handle_form_submit():
    if st.session_state.query_input and st.session_state.query_input.strip() and not st.session_state.processing:
        st.session_state.last_query = st.session_state.query_input.strip()
        st.session_state.submit_clicked = True
        # Increment the form key to force a reset
        st.session_state.form_key += 1

# Create a form with dynamic key for resetting
with st.form(key=f"query_form_{st.session_state.form_key}"):
    query = st.text_input("Ask your question:", key="query_input", 
                         placeholder="Press enter to submit your question")
    submit_button = st.form_submit_button("Get Answer", on_click=handle_form_submit, disabled=st.session_state.processing)

# Display the current question if there is one
if st.session_state.last_query:
    st.markdown("### Current Question:")
    st.info(st.session_state.last_query)

# Sliders for customization
col1, col2 = st.columns(2)
with col1:
    top_k = st.slider("Number of sources:", 3, 10, 5)
with col2:
    word_limit = st.slider("Word limit:", 50, 500, 200)

# Only process the query if explicitly submitted and not already processing
if st.session_state.submit_clicked and st.session_state.last_query and not st.session_state.processing:
    st.session_state.submit_clicked = False
    st.session_state.processing = True

    with st.spinner("Processing your question..."):
        try:
            progress_bar = st.progress(0)
            progress_bar.progress(25, "Generating embeddings...")
            
            # Call processing function with progress tracking
            progress_bar.progress(50, "Retrieving relevant passages...")
            
            result = process_query(st.session_state.last_query, top_k=top_k, word_limit=word_limit)
            
            progress_bar.progress(75, "Generating answer...")
            time.sleep(0.5)  # Small delay for visual feedback
            progress_bar.progress(100)
            
            st.subheader("Answer:")
            st.write(result["answer_with_rag"])
            st.subheader("Sources:")
            for citation in result["citations"].split("\n"):
                st.write(citation)
                
        except Exception as e:
            st.error(f"Error processing query: {str(e)}")
        finally:
            st.session_state.processing = False

# Add helpful information
st.markdown("---")
st.markdown("""
### About this app
This application uses a Retrieval-Augmented Generation (RAG) system to answer questions about Indian spiritual texts.
It searches through a database of texts to find relevant passages and generates answers based on those passages.
""")