ankanghosh commited on
Commit
be8add0
Β·
verified Β·
1 Parent(s): 404d759

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -18
app.py CHANGED
@@ -3,9 +3,11 @@ 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:
@@ -42,10 +44,17 @@ 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>
@@ -190,6 +199,14 @@ div.stInfo {
190
  text-align: center;
191
  margin-bottom: 1rem;
192
  }
 
 
 
 
 
 
 
 
193
  /* Button container for centering */
194
  .center-container {
195
  display: flex;
@@ -208,7 +225,8 @@ div.stInfo {
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
@@ -226,6 +244,7 @@ with center_col: # Put everything in the center column
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. 😊")
@@ -247,15 +266,16 @@ elif st.session_state.init_time is not None:
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, 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.
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
 
@@ -274,7 +294,16 @@ if st.session_state.show_acknowledgment:
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
@@ -284,6 +313,19 @@ def set_query(query):
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
@@ -301,7 +343,8 @@ def group_buttons(questions, max_chars_per_row=100):
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?",
@@ -327,9 +370,18 @@ for row_idx, row in enumerate(question_rows):
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():
@@ -339,7 +391,7 @@ def handle_form_submit():
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)
@@ -350,18 +402,22 @@ 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:
@@ -370,7 +426,7 @@ if st.session_state.submit_clicked and st.session_state.last_query:
370
  st.session_state.is_processing = False
371
  st.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"])
@@ -383,11 +439,12 @@ st.markdown("---")
383
 
384
  # About section with enhanced explanations
385
  st.markdown("""
386
- ### About this app
387
- **General:** This application uses a Retrieval-Augmented Generation (RAG) system to answer questions about spirituality based on insights from Indian
388
- spiritual texts. It searches through a database of texts to find relevant passages and generates answers based on those passages.
 
389
 
390
- **Techical**: The RAG pipeline is powered by an underlying large embedding model that converts texts into searchable
391
  vector representations (using FAISS indices) and a Large Language Model (LLM) that summarizes and presents the findings of the system.
392
 
393
  #### Goal
@@ -395,21 +452,23 @@ The path and journey to the SELF is designed to be undertaken alone. The all-enc
395
  Not all find the SatGuru - the true, real Guru, for guidance.
396
 
397
  It has been observed that all of the necessary knowledge for spiritual progress is available in Indian spiritual texts.
398
- Additionally, great saints, sages, siddhas, sadhus, rishis, yogis, mystics, and spiritual masters have imparted spiritual wisdom,
399
  knowledge, and guidance to beings for ages in the Indian subcontinent and beyond.
400
 
401
  Our goal is to make a small contribution to the journey of beings toward self-discovery by making this knowledge available and accessible within
402
  ethical, moral, and resource-based constraints. **We have no commercial or for-profit interests; this application is purely for educational purposes.**
403
  We sincerely hope this humble offering supports your spiritual progress. God bless.
404
 
405
- **Additionally, through this humble effort, we offer our tribute, love, and gratitude to the higher beings β€” the saints and masters β€” whose works,
406
  teachings, and wisdom have guided humanity and have inspired and informed this application.**
407
 
408
  #### Important to note
409
- - This is not a general chatbot. It is specifically designed to answer spiritual questions based on referenced texts, as against generating historical information or reproducing stories of saints or spiritual leaders.
410
  - 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.
411
  - 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.
412
  - We apologize for any inconsistencies or misinterpretations that may occur. This application is educational in nature and continuously improving.
 
 
413
 
414
  We value your feedback to enhance this application. Please visit the *Contacts* page to share your suggestions or report any issues.
415
 
@@ -417,6 +476,7 @@ For more information about the source texts used, see *Sources* in the navigatio
417
  """)
418
 
419
  # Citation note at the bottom - improved with support message
 
420
  st.markdown('<div class="citation-note">', unsafe_allow_html=True)
421
  st.markdown("""
422
  The answers presented in this application are re-presented summaries of relevant passages from the listed citations.
 
3
  import streamlit.components.v1 as components
4
 
5
  # FIRST: Set page config before ANY other Streamlit command
6
+ # Update title to "Anveshak"
7
+ st.set_page_config(page_title="Anveshak", page_icon="πŸ•‰οΈ")
8
 
9
  # Initialize ALL session state variables right at the beginning
10
+ # This ensures consistent state management across application reruns
11
  if 'initialized' not in st.session_state:
12
  st.session_state.initialized = False
13
  if 'model' not in st.session_state:
 
44
 
45
  # Function to toggle acknowledgment visibility
46
  def toggle_acknowledgment():
47
+ """Toggle the visibility of the acknowledgment section."""
48
  st.session_state.show_acknowledgment = not st.session_state.show_acknowledgment
49
 
50
  # Custom HTML/JS to navigate to sources page
51
  def navigate_to_sources():
52
+ """
53
+ Create a JavaScript function to navigate to the Sources page.
54
+
55
+ This uses Streamlit components to inject JavaScript that finds and clicks
56
+ the Sources link in the sidebar navigation.
57
+ """
58
  components.html(
59
  """
60
  <script>
 
199
  text-align: center;
200
  margin-bottom: 1rem;
201
  }
202
+ /* Subtitle styling */
203
+ .subtitle {
204
+ font-size: 1.2rem;
205
+ color: #555;
206
+ text-align: center;
207
+ margin-bottom: 1.5rem;
208
+ font-style: italic;
209
+ }
210
  /* Button container for centering */
211
  .center-container {
212
  display: flex;
 
225
  color: #6a1b9a;
226
  }
227
  </style>
228
+ <div class="main-title">Anveshak</div>
229
+ <div class="subtitle">A Spirituality Q&A Application</div>
230
  """, unsafe_allow_html=True)
231
 
232
  # Centered button layout without columns
 
244
  st.markdown('</div>', unsafe_allow_html=True)
245
 
246
  # Preload resources during initialization
247
+ # This ensures the model, index, and data are loaded before the user interacts with the app
248
  init_message = st.empty()
249
  if not st.session_state.initialized:
250
  init_message.info("Hang in there! We are setting the system up for you. 😊")
 
266
  init_message.empty()
267
  st.session_state.init_time = None
268
 
269
+ # Display the acknowledgment section if toggled on
270
  if st.session_state.show_acknowledgment:
271
  st.markdown('<div class="acknowledgment-container">', unsafe_allow_html=True)
272
  st.markdown('<div class="acknowledgment-header">A Heartfelt Thank You</div>', unsafe_allow_html=True)
273
  st.markdown("""
274
+ 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.
275
 
276
  Therefore, with deepest reverence, we express our gratitude to:
277
 
278
+ **The Saints, Sages, Siddhas, Yogis, Sadhus, Rishis, Gurus, Mystics, and Spiritual Masters** of all backgrounds, genders, and traditions 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.
279
 
280
  **The Sacred Texts** that have preserved the eternal truths across millennia, offering light in times of darkness and clarity in times of confusion.
281
 
 
294
 
295
  # Function to handle query selection from the common questions buttons
296
  def set_query(query):
297
+ """
298
+ Handle selection of a pre-defined question from the UI.
299
+
300
+ This sets the selected question as the current query, marks it for processing,
301
+ and triggers a rerun of the app to process the query.
302
+
303
+ Args:
304
+ query (str): The selected question text
305
+ """
306
+ # If already processing, ignore further input to prevent multiple submissions
307
  if st.session_state.is_processing:
308
  return
309
  st.session_state.last_query = query
 
313
 
314
  # Function to group questions into rows based on length
315
  def group_buttons(questions, max_chars_per_row=100):
316
+ """
317
+ Organize common questions into rows for better UI layout.
318
+
319
+ This function groups questions into rows based on character length to
320
+ ensure they fit well in the UI and look visually balanced.
321
+
322
+ Args:
323
+ questions (list): List of question strings
324
+ max_chars_per_row (int): Maximum total characters per row
325
+
326
+ Returns:
327
+ list: A list of rows, where each row is a list of questions
328
+ """
329
  rows = []
330
  current_row = []
331
  current_length = 0
 
343
  rows.append(current_row)
344
  return rows
345
 
346
+ # Common spiritual questions for users to select from
347
+ # These represent fundamental spiritual inquiries across traditions
348
  common_questions = [
349
  "What is the Atman or the soul?",
350
  "Are there rebirths?",
 
370
  if st.button(q, key=f"r{row_idx}_q{i}", use_container_width=True, disabled=st.session_state.is_processing):
371
  set_query(q)
372
 
373
+ # Function to handle custom question submission from the form
374
  def handle_form_submit():
375
+ """
376
+ Process user-submitted questions from the input form.
377
+
378
+ This function:
379
+ 1. Checks if a query is already being processed
380
+ 2. Validates that the input isn't empty
381
+ 3. Sets the query for processing
382
+ 4. Increments the form key to force a reset after submission
383
+ """
384
+ # If already processing, ignore further input to prevent multiple submissions
385
  if st.session_state.is_processing:
386
  return
387
  if st.session_state.query_input and st.session_state.query_input.strip():
 
391
  # Increment the form key to force a reset
392
  st.session_state.form_key += 1
393
 
394
+ # Create a form with a dynamic key (to allow resetting after submission)
395
  with st.form(key=f"query_form_{st.session_state.form_key}"):
396
  query = st.text_input("Ask your question:", key="query_input",
397
  placeholder="Press enter to submit your question", disabled=st.session_state.is_processing)
 
402
  st.markdown("### Current Question:")
403
  st.info(st.session_state.last_query)
404
 
405
+ # Sliders for customization - allows users to control retrieval parameters
406
  col1, col2 = st.columns(2)
407
  with col1:
408
+ # Control how many different sources will be used for the answer
409
  top_k = st.slider("Number of sources:", 3, 10, 5)
410
  with col2:
411
+ # Control the maximum length of the generated answer
412
  word_limit = st.slider("Word limit:", 50, 500, 200)
413
 
414
  # Process the query only if it has been explicitly submitted
415
+ # This prevents automatic processing on page load or slider adjustments
416
  if st.session_state.submit_clicked and st.session_state.last_query:
417
  st.session_state.submit_clicked = False
418
  with st.spinner("Processing your question..."):
419
  try:
420
+ # Call the RAG engine with the user's question and retrieval parameters
421
  result = process_query(st.session_state.last_query, top_k=top_k, word_limit=word_limit)
422
  st.session_state.last_answer = result # Store result in session state
423
  except Exception as e:
 
426
  st.session_state.is_processing = False
427
  st.rerun()
428
 
429
+ # Display the answer and citations if available
430
  if st.session_state.last_answer is not None:
431
  st.subheader("Answer:")
432
  st.write(st.session_state.last_answer["answer_with_rag"])
 
439
 
440
  # About section with enhanced explanations
441
  st.markdown("""
442
+ ### About Anveshak
443
+
444
+ **General:** Anveshak (meaning "seeker" in Sanskrit) is a Retrieval-Augmented Generation (RAG) system that answers questions about spirituality based on insights from Indian
445
+ spiritual texts. It searches through a database of texts to find relevant passages and generates concise answers based on those passages.
446
 
447
+ **Technical:** The RAG pipeline is powered by an underlying large embedding model that converts texts into searchable
448
  vector representations (using FAISS indices) and a Large Language Model (LLM) that summarizes and presents the findings of the system.
449
 
450
  #### Goal
 
452
  Not all find the SatGuru - the true, real Guru, for guidance.
453
 
454
  It has been observed that all of the necessary knowledge for spiritual progress is available in Indian spiritual texts.
455
+ Additionally, great Saints, Sages, Siddhas, Yogis, Sadhus, Rishis, Gurus, Mystics, and Spiritual Masters of all genders, backgrounds, and traditions have imparted spiritual wisdom,
456
  knowledge, and guidance to beings for ages in the Indian subcontinent and beyond.
457
 
458
  Our goal is to make a small contribution to the journey of beings toward self-discovery by making this knowledge available and accessible within
459
  ethical, moral, and resource-based constraints. **We have no commercial or for-profit interests; this application is purely for educational purposes.**
460
  We sincerely hope this humble offering supports your spiritual progress. God bless.
461
 
462
+ **Additionally, through this humble effort, we offer our tribute, love, and gratitude to the higher beings β€” the Saints, Sages, and Masters β€” whose works,
463
  teachings, and wisdom have guided humanity and have inspired and informed this application.**
464
 
465
  #### Important to note
466
+ - This is not a general chatbot or conversational AI. It is specifically designed to answer spiritual questions with short, concise answers based on referenced texts. It does not generate historical information, reproduce lengthy stories, create lists, or remember past conversations.
467
  - 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.
468
  - 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.
469
  - We apologize for any inconsistencies or misinterpretations that may occur. This application is educational in nature and continuously improving.
470
+ - Currently, Anveshak is only available in English.
471
+ - We do not save any user data or queries.
472
 
473
  We value your feedback to enhance this application. Please visit the *Contacts* page to share your suggestions or report any issues.
474
 
 
476
  """)
477
 
478
  # Citation note at the bottom - improved with support message
479
+ # This encourages users to purchase original works from publishers
480
  st.markdown('<div class="citation-note">', unsafe_allow_html=True)
481
  st.markdown("""
482
  The answers presented in this application are re-presented summaries of relevant passages from the listed citations.