ankanghosh commited on
Commit
fe7e3a1
·
verified ·
1 Parent(s): 54c389a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +382 -377
app.py CHANGED
@@ -2,407 +2,412 @@ import streamlit as st
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
- /* Button styling */
69
- .stButton>button {
70
- background-color: #fff0f0 !important;
71
- color: #3f51b5 !important;
72
- border: 1px solid #e1e4f2 !important;
73
- border-radius: 20px !important;
74
- padding: 8px 16px !important;
75
- box-shadow: 0 1px 2px rgba(0,0,0,0.03) !important;
76
- white-space: nowrap !important;
77
- overflow: hidden !important;
78
- text-overflow: ellipsis !important;
79
- }
80
- /* Form submit button specific styling */
81
- button[type="submit"],
82
- .stFormSubmit>button,
83
- [data-testid="stFormSubmitButton"]>button {
84
- background-color: #fff0f0 !important;
85
- color: #3f51b5 !important;
86
- border: 1px solid #e1e4f2 !important;
87
- border-radius: 8px !important;
88
- }
89
- .stButton>button:hover {
90
- background-color: #fafbff !important;
91
- border-color: #c5cae9 !important;
92
- }
93
- /* Special styling for thank you button */
94
- .thank-you-button > button {
95
- background-color: #f8e6ff !important;
96
- border-radius: 8px !important;
97
- padding: 10px 20px !important;
98
- font-weight: normal !important;
99
- box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;
100
- transition: all 0.3s ease !important;
101
- border: 1px solid #d8b9ff !important;
102
- color: #6a1b9a !important;
103
- }
104
- .thank-you-button > button:hover {
105
- background-color: #f0d6ff !important;
106
- transform: translateY(-1px) !important;
107
- }
108
- /* Input field styling */
109
- div[data-baseweb="input"] {
110
- border: 1px solid #fff0f0 !important;
111
- border-radius: 8px !important;
112
- background-color: #ffffff !important;
113
- }
114
- div[data-baseweb="input"]:focus-within {
115
- border: 1px solid #3f51b5 !important;
116
- }
117
- div[data-baseweb="input"]:active {
118
- border: 1px solid #fff0f0 !important;
119
- }
120
- /* Style the st.info boxes */
121
- div.stInfo {
122
- background-color: #f8faff !important;
123
- color: #3f51b5 !important;
124
- border: 1px solid #e1e4f2 !important;
125
- border-radius: 8px !important;
126
- }
127
- /* COMBINED SCROLL CONTAINER */
128
- .questions-scroll-container {
129
- width: 100%;
130
- overflow-x: auto;
131
- scrollbar-width: none; /* Firefox */
132
- -ms-overflow-style: none; /* IE and Edge */
133
- }
134
- /* Hide scrollbar for Chrome, Safari and Opera */
135
- .questions-scroll-container::-webkit-scrollbar {
136
- display: none;
137
- }
138
- /* Inner content that holds both rows */
139
- .questions-content {
140
- display: inline-flex;
141
- flex-direction: column;
142
- min-width: max-content;
143
- gap: 10px;
144
- padding: 5px 0;
145
- }
146
- /* Individual rows */
147
- .questions-row {
148
- display: flex;
149
- flex-direction: row;
150
- gap: 10px;
151
- }
152
- /* Placeholder for buttons */
153
- .button-placeholder {
154
- min-height: 38px;
155
- min-width: 120px;
156
- margin: 0 5px;
157
- }
158
- /* Acknowledgment section styling - fully fixed */
159
- .acknowledgment-container {
160
- background-color: #f8f5ff;
161
- border: 1px solid #e0d6fe;
162
- border-radius: 8px;
163
- padding: 15px;
164
- margin: 20px 0;
165
- box-shadow: 0 2px 5px rgba(0,0,0,0.05);
166
- }
167
- .acknowledgment-header {
168
- color: #6a1b9a;
169
- font-size: 1.3rem;
170
- margin-bottom: 10px;
171
- text-align: center;
172
- }
173
- .more-info-link {
174
- text-align: center;
175
- margin-top: 10px;
176
- font-style: italic;
177
- }
178
- .citation-note {
179
- font-size: 0.8rem;
180
- font-style: italic;
181
- color: #666;
182
- padding: 10px;
183
- border-top: 1px solid #eee;
184
- margin-top: 30px;
185
- }
186
- /* Center align title */
187
- .main-title {
188
- font-size: 2.5rem;
189
- color: #c0392b;
190
- text-align: center;
191
- margin-bottom: 1rem;
192
- }
193
- /* Button container for centering */
194
- .center-container {
195
- display: flex;
196
- justify-content: center;
197
- margin: 0 auto;
198
- width: 100%;
199
- }
200
- /* Source link styling */
201
- .source-link {
202
- color: #3f51b5;
203
- font-weight: bold;
204
- text-decoration: underline;
205
- cursor: pointer;
206
- }
207
- .source-link:hover {
208
- color: #6a1b9a;
209
- }
210
- </style>
211
- <div class="main-title">Spirituality Q&A</div>
212
- """, unsafe_allow_html=True)
213
 
214
- # Centered button layout without columns
215
- _, center_col, _ = st.columns([1, 2, 1]) # Create a wider center column
216
- with center_col: # Put everything in the center column
217
  if st.session_state.show_acknowledgment:
218
- st.markdown('<div class="thank-you-button">', unsafe_allow_html=True)
219
- if st.button("Hide Thank You Note", on_click=toggle_acknowledgment, disabled=st.session_state.is_processing, use_container_width=True):
220
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
  st.markdown('</div>', unsafe_allow_html=True)
222
- else:
223
- st.markdown('<div class="thank-you-button">', unsafe_allow_html=True)
224
- if st.button("Show Thank You Note", on_click=toggle_acknowledgment, disabled=st.session_state.is_processing, use_container_width=True):
225
- pass
226
  st.markdown('</div>', unsafe_allow_html=True)
227
 
228
- # Preload resources during initialization
229
- init_message = st.empty()
230
- if not st.session_state.initialized:
231
- init_message.info("Hang in there! We are setting the system up for you. 😊")
232
- try:
233
- # Setup authentication and preload heavy resources
234
- setup_all_auth()
235
- load_model() # This uses cached_load_model via alias
236
- cached_load_data_files() # Preload FAISS index, text chunks, and metadata
237
- st.session_state.initialized = True
238
- st.session_state.init_time = time.time()
239
- init_message.success("System initialized successfully!")
240
- time.sleep(2)
241
- init_message.empty()
242
- except Exception as e:
243
- init_message.error(f"Error initializing: {str(e)}")
244
- elif st.session_state.init_time is not None:
245
- elapsed_time = time.time() - st.session_state.init_time
246
- if elapsed_time >= 2.0:
247
- init_message.empty()
248
- st.session_state.init_time = None
249
-
250
- if st.session_state.show_acknowledgment:
251
- st.markdown('<div class="acknowledgment-container">', unsafe_allow_html=True)
252
- st.markdown('<div class="acknowledgment-header">A Heartfelt Thank You</div>', unsafe_allow_html=True)
253
- st.markdown("""
254
- 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.
255
-
256
- Therefore, with deepest reverence, we express our gratitude to:
257
-
258
- **The Saints 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.
259
-
260
- **The Sacred Texts** that have preserved the eternal truths across millennia, offering light in times of darkness and clarity in times of confusion.
261
-
262
- **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.
263
-
264
- **The Authors** who have dedicated their lives to interpreting and explaining complex spiritual concepts, making them accessible to modern readers.
265
-
266
- 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.
267
- """)
268
-
269
- # Link to Sources using Streamlit's built-in way
270
- st.markdown('<div class="more-info-link">', unsafe_allow_html=True)
271
- st.write("For detailed information about our sources, please visit the *Sources* page in the navigation menu.")
272
- st.markdown('</div>', unsafe_allow_html=True)
273
- st.markdown('</div>', unsafe_allow_html=True)
274
-
275
- # Function to handle query selection from the common questions buttons
276
- def set_query(query):
277
- # If already processing, ignore further input
278
- if st.session_state.is_processing:
279
- return
280
- st.session_state.last_query = query
281
- st.session_state.submit_clicked = True
282
- st.session_state.is_processing = True
283
- st.experimental_rerun()
284
 
285
- # Function to group questions into rows based on length
286
- def group_buttons(questions, max_chars_per_row=100):
287
- rows = []
288
- current_row = []
289
- current_length = 0
290
- for q in questions:
291
- # Add some buffer for button padding/margins
292
- q_length = len(q) + 5
293
- if current_length + q_length > max_chars_per_row and current_row:
 
 
 
 
 
 
 
294
  rows.append(current_row)
295
- current_row = [q]
296
- current_length = q_length
297
- else:
298
- current_row.append(q)
299
- current_length += q_length
300
- if current_row:
301
- rows.append(current_row)
302
- return rows
303
 
304
- # All common questions in a single list
305
- common_questions = [
306
- "What is the Atman or the soul?",
307
- "Are there rebirths?",
308
- "What is Karma?",
309
- "What is the ultimate truth?",
310
- "What is Swami Vivekananda's opinion about the SELF?",
311
- "Explain moksha or salvation. Is that for real?",
312
- "Destiny or free will?",
313
- "What is the ultimate goal of human life?",
314
- "Do we really die?",
315
- "How can you attain self-realization?"
316
- ]
317
 
318
- # Display heading for common questions
319
- st.markdown("### Common questions to try:")
320
 
321
- # Group questions into rows and create buttons (disabled if processing)
322
- question_rows = group_buttons(common_questions, max_chars_per_row=80)
323
- for row_idx, row in enumerate(question_rows):
324
- cols = st.columns(len(row))
325
- for i, (col, q) in enumerate(zip(cols, row)):
326
- with col:
327
- if st.button(q, key=f"r{row_idx}_q{i}", use_container_width=True, disabled=st.session_state.is_processing):
328
- set_query(q)
329
 
330
- # Function to handle form submission
331
- def handle_form_submit():
332
- # If already processing, ignore further input
333
- if st.session_state.is_processing:
334
- return
335
- if st.session_state.query_input and st.session_state.query_input.strip():
336
- st.session_state.last_query = st.session_state.query_input.strip()
337
- st.session_state.submit_clicked = True
338
- st.session_state.is_processing = True
339
- # Increment the form key to force a reset
340
- st.session_state.form_key += 1
341
 
342
- # Create a form with a dynamic key (to allow resetting)
343
- with st.form(key=f"query_form_{st.session_state.form_key}"):
344
- query = st.text_input("Ask your question:", key="query_input",
345
- placeholder="Press enter to submit your question", disabled=st.session_state.is_processing)
346
- submit_button = st.form_submit_button("Get Answer", on_click=handle_form_submit, disabled=st.session_state.is_processing)
347
 
348
- # Display the current question if available
349
- if st.session_state.last_query:
350
- st.markdown("### Current Question:")
351
- st.info(st.session_state.last_query)
352
 
353
- # Sliders for customization
354
- col1, col2 = st.columns(2)
355
- with col1:
356
- top_k = st.slider("Number of sources:", 3, 10, 5)
357
- with col2:
358
- word_limit = st.slider("Word limit:", 50, 500, 200)
359
 
360
- # Process the query only if it has been explicitly submitted
361
- if st.session_state.submit_clicked and st.session_state.last_query:
362
- st.session_state.submit_clicked = False
363
- with st.spinner("Processing your question..."):
364
- try:
365
- result = process_query(st.session_state.last_query, top_k=top_k, word_limit=word_limit)
366
- st.session_state.last_answer = result # Store result in session state
367
- except Exception as e:
368
- st.session_state.last_answer = {"answer_with_rag": f"Error processing query: {str(e)}", "citations": ""}
369
- # Reset debouncing after processing and force a rerun to re-enable buttons
370
- st.session_state.is_processing = False
371
- st.experimental_rerun()
372
 
373
- # Display the answer if available
374
- if st.session_state.last_answer is not None:
375
- st.subheader("Answer:")
376
- st.write(st.session_state.last_answer["answer_with_rag"])
377
- st.subheader("Sources:")
378
- for citation in st.session_state.last_answer["citations"].split("\n"):
379
- st.write(citation)
380
 
381
- # Add helpful information
382
- st.markdown("---")
383
 
384
- # About section with enhanced explanations
385
- st.markdown("""
386
- ### About this app
387
- 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.
 
 
 
 
 
 
388
 
389
- **Important to note:**
390
- - 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.
391
- - 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.
392
- - 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.
393
- - We apologize for any inconsistencies or misinterpretations that may occur. This application is educational in nature and continuously improving.
394
 
395
- We value your feedback to enhance this application. Please visit the *Contacts* page to share your suggestions or report any issues.
 
396
 
397
- For more information about the source texts used, see *Sources* in the navigation menu.
398
- """)
 
 
 
 
 
 
 
399
 
400
- # Citation note at the bottom - improved with support message
401
- st.markdown('<div class="citation-note">', unsafe_allow_html=True)
402
- st.markdown("""
403
- The answers presented in this application are re-presented summaries of relevant passages from the listed citations.
404
- For the original works in their complete and authentic form, users are respectfully encouraged to purchase
405
- the original print or digital works from their respective publishers. Your purchase helps support these publishers
406
- who have brought the world closer to such important spiritual works.
407
- """)
408
- st.markdown('</div>', unsafe_allow_html=True)
 
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()