ankanghosh commited on
Commit
b546d85
·
verified ·
1 Parent(s): 391d9c8

Update app,py

Browse files
Files changed (1) hide show
  1. app.py +385 -381
app.py CHANGED
@@ -2,412 +2,416 @@ import streamlit as st
2
  import time
3
  import streamlit.components.v1 as components
4
 
5
- def run_app():
6
- # FIRST: Set page config before ANY other Streamlit command
7
- st.set_page_config(page_title="Spirituality Q&A", page_icon="🕉️")
8
 
9
- # Initialize ALL session state variables right at the beginning
10
- if 'initialized' not in st.session_state:
11
- st.session_state.initialized = False
12
- if 'model' not in st.session_state:
13
- st.session_state.model = None
14
- if 'tokenizer' not in st.session_state:
15
- st.session_state.tokenizer = None
16
- if 'last_query' not in st.session_state:
17
- st.session_state.last_query = ""
18
- if 'submit_clicked' not in st.session_state:
19
- st.session_state.submit_clicked = False
20
- if 'init_time' not in st.session_state:
21
- st.session_state.init_time = None
22
- if 'form_key' not in st.session_state:
23
- st.session_state.form_key = 0 # This will help us reset the form
24
- # New variable for debouncing: whether processing is in progress
25
- if 'is_processing' not in st.session_state:
26
- st.session_state.is_processing = False
27
- # Store the answer so that it persists on screen
28
- if 'last_answer' not in st.session_state:
29
- st.session_state.last_answer = None
30
- # Add new session state for showing/hiding acknowledgment
31
- if 'show_acknowledgment' not in st.session_state:
32
- st.session_state.show_acknowledgment = False
33
- # Add page change detection
34
- if 'page_loaded' not in st.session_state:
35
- st.session_state.page_loaded = True
36
- # Reset query state when returning to home page
37
- st.session_state.last_query = ""
38
- st.session_state.last_answer = None
39
 
40
- # THEN: Import your modules
41
- from rag_engine import process_query, load_model, cached_load_data_files
42
- from utils import setup_all_auth
43
 
44
- # Function to toggle acknowledgment visibility
45
- def toggle_acknowledgment():
46
- st.session_state.show_acknowledgment = not st.session_state.show_acknowledgment
47
 
48
- # Custom HTML/JS to navigate to sources page
49
- def navigate_to_sources():
50
- components.html(
51
- """
52
- <script>
53
- // Wait for the page to fully load
54
- document.addEventListener('DOMContentLoaded', (event) => {
55
- // This select the nav item for the Sources page in the sidebar
56
- const sourcesLink = Array.from(document.querySelectorAll('a.css-z5fcl4')).find(el => el.innerText === 'Sources');
57
- if (sourcesLink) {
58
- sourcesLink.click();
59
- }
60
- });
61
- </script>
62
- """,
63
- height=0,
64
- )
65
 
66
- # Custom styling (pure CSS)
67
- st.markdown("""
68
- <style>
69
- /* Button styling */
70
- .stButton>button {
71
- background-color: #fff0f0 !important;
72
- color: #3f51b5 !important;
73
- border: 1px solid #e1e4f2 !important;
74
- border-radius: 20px !important;
75
- padding: 8px 16px !important;
76
- box-shadow: 0 1px 2px rgba(0,0,0,0.03) !important;
77
- white-space: nowrap !important;
78
- overflow: hidden !important;
79
- text-overflow: ellipsis !important;
80
- }
81
- /* Form submit button specific styling */
82
- button[type="submit"],
83
- .stFormSubmit>button,
84
- [data-testid="stFormSubmitButton"]>button {
85
- background-color: #fff0f0 !important;
86
- color: #3f51b5 !important;
87
- border: 1px solid #e1e4f2 !important;
88
- border-radius: 8px !important;
89
- }
90
- .stButton>button:hover {
91
- background-color: #fafbff !important;
92
- border-color: #c5cae9 !important;
93
- }
94
- /* Special styling for thank you button */
95
- .thank-you-button > button {
96
- background-color: #f8e6ff !important;
97
- border-radius: 8px !important;
98
- padding: 10px 20px !important;
99
- font-weight: normal !important;
100
- box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;
101
- transition: all 0.3s ease !important;
102
- border: 1px solid #d8b9ff !important;
103
- color: #6a1b9a !important;
104
- }
105
- .thank-you-button > button:hover {
106
- background-color: #f0d6ff !important;
107
- transform: translateY(-1px) !important;
108
- }
109
- /* Input field styling */
110
- div[data-baseweb="input"] {
111
- border: 1px solid #fff0f0 !important;
112
- border-radius: 8px !important;
113
- background-color: #ffffff !important;
114
- }
115
- div[data-baseweb="input"]:focus-within {
116
- border: 1px solid #3f51b5 !important;
117
- }
118
- div[data-baseweb="input"]:active {
119
- border: 1px solid #fff0f0 !important;
120
- }
121
- /* Style the st.info boxes */
122
- div.stInfo {
123
- background-color: #f8faff !important;
124
- color: #3f51b5 !important;
125
- border: 1px solid #e1e4f2 !important;
126
- border-radius: 8px !important;
127
- }
128
- /* COMBINED SCROLL CONTAINER */
129
- .questions-scroll-container {
130
- width: 100%;
131
- overflow-x: auto;
132
- scrollbar-width: none; /* Firefox */
133
- -ms-overflow-style: none; /* IE and Edge */
134
- }
135
- /* Hide scrollbar for Chrome, Safari and Opera */
136
- .questions-scroll-container::-webkit-scrollbar {
137
- display: none;
138
- }
139
- /* Inner content that holds both rows */
140
- .questions-content {
141
- display: inline-flex;
142
- flex-direction: column;
143
- min-width: max-content;
144
- gap: 10px;
145
- padding: 5px 0;
146
- }
147
- /* Individual rows */
148
- .questions-row {
149
- display: flex;
150
- flex-direction: row;
151
- gap: 10px;
152
- }
153
- /* Placeholder for buttons */
154
- .button-placeholder {
155
- min-height: 38px;
156
- min-width: 120px;
157
- margin: 0 5px;
158
- }
159
- /* Acknowledgment section styling - fully fixed */
160
- .acknowledgment-container {
161
- background-color: #f8f5ff;
162
- border: 1px solid #e0d6fe;
163
- border-radius: 8px;
164
- padding: 15px;
165
- margin: 20px 0;
166
- box-shadow: 0 2px 5px rgba(0,0,0,0.05);
167
- }
168
- .acknowledgment-header {
169
- color: #6a1b9a;
170
- font-size: 1.3rem;
171
- margin-bottom: 10px;
172
- text-align: center;
173
- }
174
- .more-info-link {
175
- text-align: center;
176
- margin-top: 10px;
177
- font-style: italic;
178
- }
179
- .citation-note {
180
- font-size: 0.8rem;
181
- font-style: italic;
182
- color: #666;
183
- padding: 10px;
184
- border-top: 1px solid #eee;
185
- margin-top: 30px;
186
- }
187
- /* Center align title */
188
- .main-title {
189
- font-size: 2.5rem;
190
- color: #c0392b;
191
- text-align: center;
192
- margin-bottom: 1rem;
193
- }
194
- /* Button container for centering */
195
- .center-container {
196
- display: flex;
197
- justify-content: center;
198
- margin: 0 auto;
199
- width: 100%;
200
- }
201
- /* Source link styling */
202
- .source-link {
203
- color: #3f51b5;
204
- font-weight: bold;
205
- text-decoration: underline;
206
- cursor: pointer;
207
- }
208
- .source-link:hover {
209
- color: #6a1b9a;
210
- }
211
- </style>
212
- <div class="main-title">Spirituality Q&A</div>
213
- """, unsafe_allow_html=True)
214
 
215
- # Centered button layout without columns
216
- _, center_col, _ = st.columns([1, 2, 1]) # Create a wider center column
217
- with center_col: # Put everything in the center column
218
- if st.session_state.show_acknowledgment:
219
- st.markdown('<div class="thank-you-button">', unsafe_allow_html=True)
220
- if st.button("Hide Thank You Note", on_click=toggle_acknowledgment, disabled=st.session_state.is_processing, use_container_width=True):
221
- pass
222
- st.markdown('</div>', unsafe_allow_html=True)
223
- else:
224
- st.markdown('<div class="thank-you-button">', unsafe_allow_html=True)
225
- if st.button("Show Thank You Note", on_click=toggle_acknowledgment, disabled=st.session_state.is_processing, use_container_width=True):
226
- pass
227
- st.markdown('</div>', unsafe_allow_html=True)
228
-
229
- # Preload resources during initialization
230
- init_message = st.empty()
231
- if not st.session_state.initialized:
232
- init_message.info("Hang in there! We are setting the system up for you. 😊")
233
- try:
234
- # Setup authentication and preload heavy resources
235
- setup_all_auth()
236
- load_model() # This uses cached_load_model via alias
237
- cached_load_data_files() # Preload FAISS index, text chunks, and metadata
238
- st.session_state.initialized = True
239
- st.session_state.init_time = time.time()
240
- init_message.success("System initialized successfully!")
241
- time.sleep(2)
242
- init_message.empty()
243
- except Exception as e:
244
- init_message.error(f"Error initializing: {str(e)}")
245
- elif st.session_state.init_time is not None:
246
- elapsed_time = time.time() - st.session_state.init_time
247
- if elapsed_time >= 2.0:
248
- init_message.empty()
249
- st.session_state.init_time = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
 
 
 
 
251
  if st.session_state.show_acknowledgment:
252
- st.markdown('<div class="acknowledgment-container">', unsafe_allow_html=True)
253
- st.markdown('<div class="acknowledgment-header">A Heartfelt Thank You</div>', unsafe_allow_html=True)
254
- st.markdown("""
255
- It is believed that one cannot be in a spiritual path without the will of the Lord. One need not be a believer or a non-believer, merely proceeding to thoughtlessness and observation is enough to evolve and shape perspectives. But that happens through grace. It is believed that without the will of the Lord, one cannot be blessed by real saints, and without the will of the saints, one cannot get close to them or God.
256
-
257
- Therefore, with deepest reverence, we express our gratitude to:
258
-
259
- **The Saints, Sages, Siddhas, Yogis, and Spiritual Masters** whose timeless wisdom illuminates this application. From ancient sages to modern masters, their selfless dedication to uplift humanity through selfless love and spiritual knowledge continues to guide seekers on the path.
260
-
261
- **The Sacred Texts** that have preserved the eternal truths across millennia, offering light in times of darkness and clarity in times of confusion.
262
-
263
- **The Publishers** who have diligently preserved and disseminated these precious teachings, making them accessible to spiritual aspirants worldwide. Their work ensures these wisdom traditions endure for future generations.
264
-
265
- **The Authors** who have dedicated their lives to interpreting and explaining complex spiritual concepts, making them accessible to modern readers.
266
-
267
- This application is merely a humble vessel for the ocean of wisdom they have shared with the world. We claim no ownership of these teachings - only profound gratitude for the opportunity to help make them more accessible.
268
- """)
269
-
270
- # Link to Sources using Streamlit's built-in way
271
- st.markdown('<div class="more-info-link">', unsafe_allow_html=True)
272
- st.write("For detailed information about our sources, please visit the *Sources* page in the navigation menu.")
273
  st.markdown('</div>', unsafe_allow_html=True)
 
 
 
 
274
  st.markdown('</div>', unsafe_allow_html=True)
275
 
276
- # Function to handle query selection from the common questions buttons
277
- def set_query(query):
278
- # If already processing, ignore further input
279
- if st.session_state.is_processing:
280
- return
281
- st.session_state.last_query = query
282
- st.session_state.submit_clicked = True
283
- st.session_state.is_processing = True
284
- st.experimental_rerun()
 
 
 
 
 
 
 
 
 
 
 
 
285
 
286
- # Function to group questions into rows based on length
287
- def group_buttons(questions, max_chars_per_row=100):
288
- rows = []
289
- current_row = []
290
- current_length = 0
291
- for q in questions:
292
- # Add some buffer for button padding/margins
293
- q_length = len(q) + 5
294
- if current_length + q_length > max_chars_per_row and current_row:
295
- rows.append(current_row)
296
- current_row = [q]
297
- current_length = q_length
298
- else:
299
- current_row.append(q)
300
- current_length += q_length
301
- if current_row:
302
- rows.append(current_row)
303
- return rows
 
 
 
 
 
 
304
 
305
- # All common questions in a single list
306
- common_questions = [
307
- "What is the Atman or the soul?",
308
- "Are there rebirths?",
309
- "What is Karma?",
310
- "What is the ultimate truth?",
311
- "What is Swami Vivekananda's opinion about the SELF?",
312
- "Explain moksha or salvation. Is that for real?",
313
- "Destiny or free will?",
314
- "What is the ultimate goal of human life?",
315
- "Do we really die?",
316
- "How can you attain self-realization?"
317
- ]
318
 
319
- # Display heading for common questions
320
- st.markdown("### Few questions to try:")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
321
 
322
- # Group questions into rows and create buttons (disabled if processing)
323
- question_rows = group_buttons(common_questions, max_chars_per_row=80)
324
- for row_idx, row in enumerate(question_rows):
325
- cols = st.columns(len(row))
326
- for i, (col, q) in enumerate(zip(cols, row)):
327
- with col:
328
- if st.button(q, key=f"r{row_idx}_q{i}", use_container_width=True, disabled=st.session_state.is_processing):
329
- set_query(q)
 
 
 
 
 
330
 
331
- # Function to handle form submission
332
- def handle_form_submit():
333
- # If already processing, ignore further input
334
- if st.session_state.is_processing:
335
- return
336
- if st.session_state.query_input and st.session_state.query_input.strip():
337
- st.session_state.last_query = st.session_state.query_input.strip()
338
- st.session_state.submit_clicked = True
339
- st.session_state.is_processing = True
340
- # Increment the form key to force a reset
341
- st.session_state.form_key += 1
342
 
343
- # Create a form with a dynamic key (to allow resetting)
344
- with st.form(key=f"query_form_{st.session_state.form_key}"):
345
- query = st.text_input("Ask your question:", key="query_input",
346
- placeholder="Press enter to submit your question", disabled=st.session_state.is_processing)
347
- submit_button = st.form_submit_button("Get Answer", on_click=handle_form_submit, disabled=st.session_state.is_processing)
 
 
 
348
 
349
- # Display the current question if available
350
- if st.session_state.last_query:
351
- st.markdown("### Current Question:")
352
- st.info(st.session_state.last_query)
 
 
 
 
 
 
 
353
 
354
- # Sliders for customization
355
- col1, col2 = st.columns(2)
356
- with col1:
357
- top_k = st.slider("Number of sources:", 3, 10, 5)
358
- with col2:
359
- word_limit = st.slider("Word limit:", 50, 500, 200)
360
 
361
- # Process the query only if it has been explicitly submitted
362
- if st.session_state.submit_clicked and st.session_state.last_query:
363
- st.session_state.submit_clicked = False
364
- with st.spinner("Processing your question..."):
365
- try:
366
- result = process_query(st.session_state.last_query, top_k=top_k, word_limit=word_limit)
367
- st.session_state.last_answer = result # Store result in session state
368
- except Exception as e:
369
- st.session_state.last_answer = {"answer_with_rag": f"Error processing query: {str(e)}", "citations": ""}
370
- # Reset debouncing after processing and force a rerun to re-enable buttons
371
- st.session_state.is_processing = False
372
- st.experimental_rerun()
373
 
374
- # Display the answer if available
375
- if st.session_state.last_answer is not None:
376
- st.subheader("Answer:")
377
- st.write(st.session_state.last_answer["answer_with_rag"])
378
- st.subheader("Sources:")
379
- for citation in st.session_state.last_answer["citations"].split("\n"):
380
- st.write(citation)
381
 
382
- # Add helpful information
383
- st.markdown("---")
 
 
 
 
 
 
 
 
 
 
384
 
385
- # About section with enhanced explanations
386
- st.markdown("""
387
- ### About this app
388
- This application uses a Retrieval-Augmented Generation (RAG) system to answer questions about spirituality based on insights from Indian spiritual texts. It searches through a database of texts to find relevant passages and generates answers based on those passages.
 
 
 
389
 
390
- **Important to note:**
391
- - This is not a general chatbot. It is specifically designed to answer spiritual questions based on referenced texts, not to generate historical information or reproduce stories of saints or spiritual leaders.
392
- - You may receive slightly different answers when asking the same question multiple times. This variation is intentional and reflects the nuanced nature of spiritual teachings across different traditions.
393
- - While you can select a specific number of citations and word limit, the actual response may contain fewer citations based on relevance and availability of information. Similarly, explanations may be shorter than the selected word limit if the retrieved information is concise.
394
- - We apologize for any inconsistencies or misinterpretations that may occur. This application is educational in nature and continuously improving.
395
 
396
- We value your feedback to enhance this application. Please visit the *Contacts* page to share your suggestions or report any issues.
 
 
 
397
 
398
- For more information about the source texts used, see *Sources* in the navigation menu.
399
- """)
 
 
 
400
 
401
- # Citation note at the bottom - improved with support message
402
- st.markdown('<div class="citation-note">', unsafe_allow_html=True)
403
- st.markdown("""
404
- The answers presented in this application are re-presented summaries of relevant passages from the listed citations.
405
- For the original works in their complete and authentic form, users are respectfully encouraged to purchase
406
- the original print or digital works from their respective publishers. Your purchase helps support these publishers
407
- who have brought the world closer to such important spiritual works.
408
- """)
409
- st.markdown('</div>', unsafe_allow_html=True)
410
 
411
- # Run the app if this script is executed directly
412
- if __name__ == "__main__":
413
- run_app()
 
 
 
 
 
 
 
2
  import time
3
  import streamlit.components.v1 as components
4
 
5
+ # FIRST: Set page config before ANY other Streamlit command
6
+ st.set_page_config(page_title="Spirituality Q&A", page_icon="🕉️")
 
7
 
8
+ # Initialize ALL session state variables right at the beginning
9
+ if 'initialized' not in st.session_state:
10
+ st.session_state.initialized = False
11
+ if 'model' not in st.session_state:
12
+ st.session_state.model = None
13
+ if 'tokenizer' not in st.session_state:
14
+ st.session_state.tokenizer = None
15
+ if 'last_query' not in st.session_state:
16
+ st.session_state.last_query = ""
17
+ if 'submit_clicked' not in st.session_state:
18
+ st.session_state.submit_clicked = False
19
+ if 'init_time' not in st.session_state:
20
+ st.session_state.init_time = None
21
+ if 'form_key' not in st.session_state:
22
+ st.session_state.form_key = 0 # This will help us reset the form
23
+ # New variable for debouncing: whether processing is in progress
24
+ if 'is_processing' not in st.session_state:
25
+ st.session_state.is_processing = False
26
+ # Store the answer so that it persists on screen
27
+ if 'last_answer' not in st.session_state:
28
+ st.session_state.last_answer = None
29
+ # Add new session state for showing/hiding acknowledgment
30
+ if 'show_acknowledgment' not in st.session_state:
31
+ st.session_state.show_acknowledgment = False
32
+ # Add page change detection
33
+ if 'page_loaded' not in st.session_state:
34
+ st.session_state.page_loaded = True
35
+ # Reset query state when returning to home page
36
+ st.session_state.last_query = ""
37
+ st.session_state.last_answer = None
38
 
39
+ # THEN: Import your modules
40
+ from rag_engine import process_query, load_model, cached_load_data_files
41
+ from utils import setup_all_auth
42
 
43
+ # Function to toggle acknowledgment visibility
44
+ def toggle_acknowledgment():
45
+ st.session_state.show_acknowledgment = not st.session_state.show_acknowledgment
46
 
47
+ # Custom HTML/JS to navigate to sources page
48
+ def navigate_to_sources():
49
+ components.html(
50
+ """
51
+ <script>
52
+ // Wait for the page to fully load
53
+ document.addEventListener('DOMContentLoaded', (event) => {
54
+ // This select the nav item for the Sources page in the sidebar
55
+ const sourcesLink = Array.from(document.querySelectorAll('a.css-z5fcl4')).find(el => el.innerText === 'Sources');
56
+ if (sourcesLink) {
57
+ sourcesLink.click();
58
+ }
59
+ });
60
+ </script>
61
+ """,
62
+ height=0,
63
+ )
64
 
65
+ # Custom styling (pure CSS)
66
+ st.markdown("""
67
+ <style>
68
+ /* Change sidebar labels */
69
+ [data-testid="stSidebarNav"] ul li:first-child p {
70
+ font-size: 0px;
71
+ }
72
+ [data-testid="stSidebarNav"] ul li:first-child p::after {
73
+ content: "Home";
74
+ font-size: 14px;
75
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
+ /* Button styling */
78
+ .stButton>button {
79
+ background-color: #fff0f0 !important;
80
+ color: #3f51b5 !important;
81
+ border: 1px solid #e1e4f2 !important;
82
+ border-radius: 20px !important;
83
+ padding: 8px 16px !important;
84
+ box-shadow: 0 1px 2px rgba(0,0,0,0.03) !important;
85
+ white-space: nowrap !important;
86
+ overflow: hidden !important;
87
+ text-overflow: ellipsis !important;
88
+ }
89
+ /* Form submit button specific styling */
90
+ button[type="submit"],
91
+ .stFormSubmit>button,
92
+ [data-testid="stFormSubmitButton"]>button {
93
+ background-color: #fff0f0 !important;
94
+ color: #3f51b5 !important;
95
+ border: 1px solid #e1e4f2 !important;
96
+ border-radius: 8px !important;
97
+ }
98
+ .stButton>button:hover {
99
+ background-color: #fafbff !important;
100
+ border-color: #c5cae9 !important;
101
+ }
102
+ /* Special styling for thank you button */
103
+ .thank-you-button > button {
104
+ background-color: #f8e6ff !important;
105
+ border-radius: 8px !important;
106
+ padding: 10px 20px !important;
107
+ font-weight: normal !important;
108
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;
109
+ transition: all 0.3s ease !important;
110
+ border: 1px solid #d8b9ff !important;
111
+ color: #6a1b9a !important;
112
+ }
113
+ .thank-you-button > button:hover {
114
+ background-color: #f0d6ff !important;
115
+ transform: translateY(-1px) !important;
116
+ }
117
+ /* Input field styling */
118
+ div[data-baseweb="input"] {
119
+ border: 1px solid #fff0f0 !important;
120
+ border-radius: 8px !important;
121
+ background-color: #ffffff !important;
122
+ }
123
+ div[data-baseweb="input"]:focus-within {
124
+ border: 1px solid #3f51b5 !important;
125
+ }
126
+ div[data-baseweb="input"]:active {
127
+ border: 1px solid #fff0f0 !important;
128
+ }
129
+ /* Style the st.info boxes */
130
+ div.stInfo {
131
+ background-color: #f8faff !important;
132
+ color: #3f51b5 !important;
133
+ border: 1px solid #e1e4f2 !important;
134
+ border-radius: 8px !important;
135
+ }
136
+ /* COMBINED SCROLL CONTAINER */
137
+ .questions-scroll-container {
138
+ width: 100%;
139
+ overflow-x: auto;
140
+ scrollbar-width: none; /* Firefox */
141
+ -ms-overflow-style: none; /* IE and Edge */
142
+ }
143
+ /* Hide scrollbar for Chrome, Safari and Opera */
144
+ .questions-scroll-container::-webkit-scrollbar {
145
+ display: none;
146
+ }
147
+ /* Inner content that holds both rows */
148
+ .questions-content {
149
+ display: inline-flex;
150
+ flex-direction: column;
151
+ min-width: max-content;
152
+ gap: 10px;
153
+ padding: 5px 0;
154
+ }
155
+ /* Individual rows */
156
+ .questions-row {
157
+ display: flex;
158
+ flex-direction: row;
159
+ gap: 10px;
160
+ }
161
+ /* Placeholder for buttons */
162
+ .button-placeholder {
163
+ min-height: 38px;
164
+ min-width: 120px;
165
+ margin: 0 5px;
166
+ }
167
+ /* Acknowledgment section styling - fully fixed */
168
+ .acknowledgment-container {
169
+ background-color: #f8f5ff;
170
+ border: 1px solid #e0d6fe;
171
+ border-radius: 8px;
172
+ padding: 15px;
173
+ margin: 20px 0;
174
+ box-shadow: 0 2px 5px rgba(0,0,0,0.05);
175
+ }
176
+ .acknowledgment-header {
177
+ color: #6a1b9a;
178
+ font-size: 1.3rem;
179
+ margin-bottom: 10px;
180
+ text-align: center;
181
+ }
182
+ .more-info-link {
183
+ text-align: center;
184
+ margin-top: 10px;
185
+ font-style: italic;
186
+ }
187
+ .citation-note {
188
+ font-size: 0.8rem;
189
+ font-style: italic;
190
+ color: #666;
191
+ padding: 10px;
192
+ border-top: 1px solid #eee;
193
+ margin-top: 30px;
194
+ }
195
+ /* Center align title */
196
+ .main-title {
197
+ font-size: 2.5rem;
198
+ color: #c0392b;
199
+ text-align: center;
200
+ margin-bottom: 1rem;
201
+ }
202
+ /* Button container for centering */
203
+ .center-container {
204
+ display: flex;
205
+ justify-content: center;
206
+ margin: 0 auto;
207
+ width: 100%;
208
+ }
209
+ /* Source link styling */
210
+ .source-link {
211
+ color: #3f51b5;
212
+ font-weight: bold;
213
+ text-decoration: underline;
214
+ cursor: pointer;
215
+ }
216
+ .source-link:hover {
217
+ color: #6a1b9a;
218
+ }
219
+ </style>
220
+ <div class="main-title">Spirituality Q&A</div>
221
+ """, unsafe_allow_html=True)
222
 
223
+ # Centered button layout without columns
224
+ _, center_col, _ = st.columns([1, 2, 1]) # Create a wider center column
225
+ with center_col: # Put everything in the center column
226
  if st.session_state.show_acknowledgment:
227
+ st.markdown('<div class="thank-you-button">', unsafe_allow_html=True)
228
+ if st.button("Hide Thank You Note", on_click=toggle_acknowledgment, disabled=st.session_state.is_processing, use_container_width=True):
229
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
  st.markdown('</div>', unsafe_allow_html=True)
231
+ else:
232
+ st.markdown('<div class="thank-you-button">', unsafe_allow_html=True)
233
+ if st.button("Show Thank You Note", on_click=toggle_acknowledgment, disabled=st.session_state.is_processing, use_container_width=True):
234
+ pass
235
  st.markdown('</div>', unsafe_allow_html=True)
236
 
237
+ # Preload resources during initialization
238
+ init_message = st.empty()
239
+ if not st.session_state.initialized:
240
+ init_message.info("Hang in there! We are setting the system up for you. 😊")
241
+ try:
242
+ # Setup authentication and preload heavy resources
243
+ setup_all_auth()
244
+ load_model() # This uses cached_load_model via alias
245
+ cached_load_data_files() # Preload FAISS index, text chunks, and metadata
246
+ st.session_state.initialized = True
247
+ st.session_state.init_time = time.time()
248
+ init_message.success("System initialized successfully!")
249
+ time.sleep(2)
250
+ init_message.empty()
251
+ except Exception as e:
252
+ init_message.error(f"Error initializing: {str(e)}")
253
+ elif st.session_state.init_time is not None:
254
+ elapsed_time = time.time() - st.session_state.init_time
255
+ if elapsed_time >= 2.0:
256
+ init_message.empty()
257
+ st.session_state.init_time = None
258
 
259
+ if st.session_state.show_acknowledgment:
260
+ st.markdown('<div class="acknowledgment-container">', unsafe_allow_html=True)
261
+ st.markdown('<div class="acknowledgment-header">A Heartfelt Thank You</div>', unsafe_allow_html=True)
262
+ st.markdown("""
263
+ It is believed that one cannot be in a spiritual path without the will of the Lord. One need not be a believer or a non-believer, merely proceeding to thoughtlessness and observation is enough to evolve and shape perspectives. But that happens through grace. It is believed that without the will of the Lord, one cannot be blessed by real saints, and without the will of the saints, one cannot get close to them or God.
264
+
265
+ Therefore, with deepest reverence, we express our gratitude to:
266
+
267
+ **The Saints, Sages, Siddhas, Yogis, and Spiritual Masters** whose timeless wisdom illuminates this application. From ancient sages to modern masters, their selfless dedication to uplift humanity through selfless love and spiritual knowledge continues to guide seekers on the path.
268
+
269
+ **The Sacred Texts** that have preserved the eternal truths across millennia, offering light in times of darkness and clarity in times of confusion.
270
+
271
+ **The Publishers** who have diligently preserved and disseminated these precious teachings, making them accessible to spiritual aspirants worldwide. Their work ensures these wisdom traditions endure for future generations.
272
+
273
+ **The Authors** who have dedicated their lives to interpreting and explaining complex spiritual concepts, making them accessible to modern readers.
274
+
275
+ This application is merely a humble vessel for the ocean of wisdom they have shared with the world. We claim no ownership of these teachings - only profound gratitude for the opportunity to help make them more accessible.
276
+ """)
277
+
278
+ # Link to Sources using Streamlit's built-in way
279
+ st.markdown('<div class="more-info-link">', unsafe_allow_html=True)
280
+ st.write("For detailed information about our sources, please visit the *Sources* page in the navigation menu.")
281
+ st.markdown('</div>', unsafe_allow_html=True)
282
+ st.markdown('</div>', unsafe_allow_html=True)
283
 
284
+ # Function to handle query selection from the common questions buttons
285
+ def set_query(query):
286
+ # If already processing, ignore further input
287
+ if st.session_state.is_processing:
288
+ return
289
+ st.session_state.last_query = query
290
+ st.session_state.submit_clicked = True
291
+ st.session_state.is_processing = True
292
+ st.experimental_rerun()
 
 
 
 
293
 
294
+ # Function to group questions into rows based on length
295
+ def group_buttons(questions, max_chars_per_row=100):
296
+ rows = []
297
+ current_row = []
298
+ current_length = 0
299
+ for q in questions:
300
+ # Add some buffer for button padding/margins
301
+ q_length = len(q) + 5
302
+ if current_length + q_length > max_chars_per_row and current_row:
303
+ rows.append(current_row)
304
+ current_row = [q]
305
+ current_length = q_length
306
+ else:
307
+ current_row.append(q)
308
+ current_length += q_length
309
+ if current_row:
310
+ rows.append(current_row)
311
+ return rows
312
 
313
+ # All common questions in a single list
314
+ common_questions = [
315
+ "What is the Atman or the soul?",
316
+ "Are there rebirths?",
317
+ "What is Karma?",
318
+ "What is the ultimate truth?",
319
+ "What is Swami Vivekananda's opinion about the SELF?",
320
+ "Explain moksha or salvation. Is that for real?",
321
+ "Destiny or free will?",
322
+ "What is the ultimate goal of human life?",
323
+ "Do we really die?",
324
+ "How can you attain self-realization?"
325
+ ]
326
 
327
+ # Display heading for common questions
328
+ st.markdown("### Few questions to try:")
 
 
 
 
 
 
 
 
 
329
 
330
+ # Group questions into rows and create buttons (disabled if processing)
331
+ question_rows = group_buttons(common_questions, max_chars_per_row=80)
332
+ for row_idx, row in enumerate(question_rows):
333
+ cols = st.columns(len(row))
334
+ for i, (col, q) in enumerate(zip(cols, row)):
335
+ with col:
336
+ if st.button(q, key=f"r{row_idx}_q{i}", use_container_width=True, disabled=st.session_state.is_processing):
337
+ set_query(q)
338
 
339
+ # Function to handle form submission
340
+ def handle_form_submit():
341
+ # If already processing, ignore further input
342
+ if st.session_state.is_processing:
343
+ return
344
+ if st.session_state.query_input and st.session_state.query_input.strip():
345
+ st.session_state.last_query = st.session_state.query_input.strip()
346
+ st.session_state.submit_clicked = True
347
+ st.session_state.is_processing = True
348
+ # Increment the form key to force a reset
349
+ st.session_state.form_key += 1
350
 
351
+ # Create a form with a dynamic key (to allow resetting)
352
+ with st.form(key=f"query_form_{st.session_state.form_key}"):
353
+ query = st.text_input("Ask your question:", key="query_input",
354
+ placeholder="Press enter to submit your question", disabled=st.session_state.is_processing)
355
+ submit_button = st.form_submit_button("Get Answer", on_click=handle_form_submit, disabled=st.session_state.is_processing)
 
356
 
357
+ # Display the current question if available
358
+ if st.session_state.last_query:
359
+ st.markdown("### Current Question:")
360
+ st.info(st.session_state.last_query)
 
 
 
 
 
 
 
 
361
 
362
+ # Sliders for customization
363
+ col1, col2 = st.columns(2)
364
+ with col1:
365
+ top_k = st.slider("Number of sources:", 3, 10, 5)
366
+ with col2:
367
+ word_limit = st.slider("Word limit:", 50, 500, 200)
 
368
 
369
+ # Process the query only if it has been explicitly submitted
370
+ if st.session_state.submit_clicked and st.session_state.last_query:
371
+ st.session_state.submit_clicked = False
372
+ with st.spinner("Processing your question..."):
373
+ try:
374
+ result = process_query(st.session_state.last_query, top_k=top_k, word_limit=word_limit)
375
+ st.session_state.last_answer = result # Store result in session state
376
+ except Exception as e:
377
+ st.session_state.last_answer = {"answer_with_rag": f"Error processing query: {str(e)}", "citations": ""}
378
+ # Reset debouncing after processing and force a rerun to re-enable buttons
379
+ st.session_state.is_processing = False
380
+ st.experimental_rerun()
381
 
382
+ # Display the answer if available
383
+ if st.session_state.last_answer is not None:
384
+ st.subheader("Answer:")
385
+ st.write(st.session_state.last_answer["answer_with_rag"])
386
+ st.subheader("Sources:")
387
+ for citation in st.session_state.last_answer["citations"].split("\n"):
388
+ st.write(citation)
389
 
390
+ # Add helpful information
391
+ st.markdown("---")
 
 
 
392
 
393
+ # About section with enhanced explanations
394
+ st.markdown("""
395
+ ### About this app
396
+ This application uses a Retrieval-Augmented Generation (RAG) system to answer questions about spirituality based on insights from Indian spiritual texts. It searches through a database of texts to find relevant passages and generates answers based on those passages.
397
 
398
+ **Important to note:**
399
+ - This is not a general chatbot. It is specifically designed to answer spiritual questions based on referenced texts, not to generate historical information or reproduce stories of saints or spiritual leaders.
400
+ - You may receive slightly different answers when asking the same question multiple times. This variation is intentional and reflects the nuanced nature of spiritual teachings across different traditions.
401
+ - While you can select a specific number of citations and word limit, the actual response may contain fewer citations based on relevance and availability of information. Similarly, explanations may be shorter than the selected word limit if the retrieved information is concise.
402
+ - We apologize for any inconsistencies or misinterpretations that may occur. This application is educational in nature and continuously improving.
403
 
404
+ We value your feedback to enhance this application. Please visit the *Contacts* page to share your suggestions or report any issues.
405
+
406
+ For more information about the source texts used, see *Sources* in the navigation menu.
407
+ """)
 
 
 
 
 
408
 
409
+ # Citation note at the bottom - improved with support message
410
+ st.markdown('<div class="citation-note">', unsafe_allow_html=True)
411
+ st.markdown("""
412
+ The answers presented in this application are re-presented summaries of relevant passages from the listed citations.
413
+ For the original works in their complete and authentic form, users are respectfully encouraged to purchase
414
+ the original print or digital works from their respective publishers. Your purchase helps support these publishers
415
+ who have brought the world closer to such important spiritual works.
416
+ """)
417
+ st.markdown('</div>', unsafe_allow_html=True)