ankanghosh commited on
Commit
5c5da11
·
verified ·
1 Parent(s): bf596d1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -7
app.py CHANGED
@@ -51,7 +51,7 @@ def navigate_to_sources():
51
  <script>
52
  // Wait for the page to fully load
53
  document.addEventListener('DOMContentLoaded', (event) => {
54
- // This selects 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();
@@ -212,8 +212,8 @@ div.stInfo {
212
  """, unsafe_allow_html=True)
213
 
214
  # Centered button layout without columns
215
- _, center_col, _ = st.columns([1, 2, 1])
216
- with center_col:
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):
@@ -230,8 +230,9 @@ 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_all_auth()
234
- load_model() # Uses cached_load_model via alias
235
  cached_load_data_files() # Preload FAISS index, text chunks, and metadata
236
  st.session_state.initialized = True
237
  st.session_state.init_time = time.time()
@@ -264,6 +265,8 @@ if st.session_state.show_acknowledgment:
264
 
265
  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.
266
  """)
 
 
267
  st.markdown('<div class="more-info-link">', unsafe_allow_html=True)
268
  st.write("For detailed information about our sources, please visit the *Sources* page in the navigation menu.")
269
  st.markdown('</div>', unsafe_allow_html=True)
@@ -271,12 +274,13 @@ if st.session_state.show_acknowledgment:
271
 
272
  # Function to handle query selection from the common questions buttons
273
  def set_query(query):
 
274
  if st.session_state.is_processing:
275
  return
276
  st.session_state.last_query = query
277
  st.session_state.submit_clicked = True
278
  st.session_state.is_processing = True
279
- # No explicit rerun here; widget interaction already triggers a re-run
280
 
281
  # Function to group questions into rows based on length
282
  def group_buttons(questions, max_chars_per_row=100):
@@ -284,6 +288,7 @@ def group_buttons(questions, max_chars_per_row=100):
284
  current_row = []
285
  current_length = 0
286
  for q in questions:
 
287
  q_length = len(q) + 5
288
  if current_length + q_length > max_chars_per_row and current_row:
289
  rows.append(current_row)
@@ -296,6 +301,7 @@ def group_buttons(questions, max_chars_per_row=100):
296
  rows.append(current_row)
297
  return rows
298
 
 
299
  common_questions = [
300
  "What is the Atman or the soul?",
301
  "Are there rebirths?",
@@ -309,7 +315,10 @@ common_questions = [
309
  "How can you attain self-realization?"
310
  ]
311
 
 
312
  st.markdown("### Few questions to try:")
 
 
313
  question_rows = group_buttons(common_questions, max_chars_per_row=80)
314
  for row_idx, row in enumerate(question_rows):
315
  cols = st.columns(len(row))
@@ -320,39 +329,48 @@ for row_idx, row in enumerate(question_rows):
320
 
321
  # Function to handle form submission
322
  def handle_form_submit():
 
323
  if st.session_state.is_processing:
324
  return
325
  if st.session_state.query_input and st.session_state.query_input.strip():
326
  st.session_state.last_query = st.session_state.query_input.strip()
327
  st.session_state.submit_clicked = True
328
  st.session_state.is_processing = True
 
329
  st.session_state.form_key += 1
330
 
 
331
  with st.form(key=f"query_form_{st.session_state.form_key}"):
332
  query = st.text_input("Ask your question:", key="query_input",
333
  placeholder="Press enter to submit your question", disabled=st.session_state.is_processing)
334
  submit_button = st.form_submit_button("Get Answer", on_click=handle_form_submit, disabled=st.session_state.is_processing)
335
 
 
336
  if st.session_state.last_query:
337
  st.markdown("### Current Question:")
338
  st.info(st.session_state.last_query)
339
 
 
340
  col1, col2 = st.columns(2)
341
  with col1:
342
  top_k = st.slider("Number of sources:", 3, 10, 5)
343
  with col2:
344
  word_limit = st.slider("Word limit:", 50, 500, 200)
345
 
 
346
  if st.session_state.submit_clicked and st.session_state.last_query:
347
  st.session_state.submit_clicked = False
348
  with st.spinner("Processing your question..."):
349
  try:
350
  result = process_query(st.session_state.last_query, top_k=top_k, word_limit=word_limit)
351
- st.session_state.last_answer = result
352
  except Exception as e:
353
  st.session_state.last_answer = {"answer_with_rag": f"Error processing query: {str(e)}", "citations": ""}
354
- st.session_state.is_processing = False # Reset processing flag
 
 
355
 
 
356
  if st.session_state.last_answer is not None:
357
  st.subheader("Answer:")
358
  st.write(st.session_state.last_answer["answer_with_rag"])
@@ -360,7 +378,10 @@ if st.session_state.last_answer is not None:
360
  for citation in st.session_state.last_answer["citations"].split("\n"):
361
  st.write(citation)
362
 
 
363
  st.markdown("---")
 
 
364
  st.markdown("""
365
  ### About this app
366
  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.
@@ -376,6 +397,7 @@ We value your feedback to enhance this application. Please visit the *Contacts*
376
  For more information about the source texts used, see *Sources* in the navigation menu.
377
  """)
378
 
 
379
  st.markdown('<div class="citation-note">', unsafe_allow_html=True)
380
  st.markdown("""
381
  The answers presented in this application are re-presented summaries of relevant passages from the listed citations.
 
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();
 
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):
 
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()
 
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)
 
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.rerun()
284
 
285
  # Function to group questions into rows based on length
286
  def group_buttons(questions, max_chars_per_row=100):
 
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)
 
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?",
 
315
  "How can you attain self-realization?"
316
  ]
317
 
318
+ # Display heading for common questions
319
  st.markdown("### Few 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))
 
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.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"])
 
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.
 
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.