anveshak / app.py
ankanghosh's picture
Update app.py
8dfb503 verified
raw
history blame
6.03 kB
import streamlit as st
import time
# FIRST: Set page config before ANY other Streamlit command
st.set_page_config(page_title="Indian Spiritual RAG")
# THEN: Import your modules
from rag_engine import process_query, load_model
from utils import setup_all_auth
# Initialize session state variables (at the very top)
if 'initialized' not in st.session_state:
st.session_state.initialized = False
if 'last_query' not in st.session_state:
st.session_state.last_query = ""
if 'submit_clicked' not in st.session_state:
st.session_state.submit_clicked = False
if 'show_success' not in st.session_state:
st.session_state.show_success = False
if 'success_time' not in st.session_state:
st.session_state.success_time = None
# Display title with custom styling
st.markdown("""
<style>
.main-title {
font-size: 2.5rem;
color: #FF5722;
text-align: center;
margin-bottom: 1rem;
}
.stButton>button {
border: 2px solid #FF5722 !important;
border-radius: 8px !important;
}
/* Remove any default styling for input fields */
div[data-baseweb="input"] {
border: none !important;
box-shadow: none !important;
}
div[data-baseweb="input"] > div {
background-color: transparent !important;
}
div[data-baseweb="input"] > div > div {
box-shadow: none !important;
}
.stTextInput>div>div>input {
border: 2px solid #4CAF50 !important;
border-radius: 8px !important;
box-shadow: none !important;
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
function applyInputStyles() {
const inputs = document.querySelectorAll('.stTextInput input');
inputs.forEach(function(input) {
// Clean up old event listeners if any
const newInput = input.cloneNode(true);
input.parentNode.replaceChild(newInput, input);
// Set initial green border
newInput.style.border = '2px solid #4CAF50';
newInput.style.borderRadius = '8px';
newInput.style.boxShadow = 'none';
// Focus - change to red
newInput.addEventListener('focus', function() {
this.style.border = '2px solid #FF5722';
this.style.borderRadius = '8px';
this.style.boxShadow = 'none';
});
// Blur - back to green
newInput.addEventListener('blur', function() {
this.style.border = '2px solid #4CAF50';
this.style.borderRadius = '8px';
this.style.boxShadow = 'none';
});
});
}
// Run initially
applyInputStyles();
// Watch for changes
const observer = new MutationObserver(function() {
applyInputStyles();
});
observer.observe(document.body, {
childList: true,
subtree: true
});
});
</script>
<div class="main-title">Indian Spiritual Texts Q&A</div>
""", unsafe_allow_html=True)
# Create placeholder for initialization message
init_message = st.empty()
# Handle initialization only once
if not st.session_state.initialized:
# Show the loading message
init_message.info("Hang in there! We are setting the system up for you. 😊")
try:
# Setup authentication
setup_all_auth()
# Force model loading
load_model()
# Mark as initialized
st.session_state.initialized = True
# Set flags to show success message temporarily
st.session_state.show_success = True
st.session_state.success_time = time.time()
# Show success message
init_message.success("System initialized successfully!")
except Exception as e:
init_message.error(f"Error initializing: {str(e)}")
st.stop() # Stop execution if initialization fails
else:
# Check if we need to clear the success message
current_time = time.time()
if st.session_state.show_success:
if current_time - st.session_state.success_time > 2:
init_message.empty()
st.session_state.show_success = False
# Function to process when enter is pressed or button is clicked
def process_input():
st.session_state.last_query = st.session_state.query_input
st.session_state.query_input = ""
st.session_state.submit_clicked = True
# Query input with callback for Enter key
query = st.text_input(
"Ask your question:",
key="query_input",
on_change=process_input
)
# Display the current question if there is one
if st.session_state.last_query:
st.markdown("### Current Question:")
st.info(st.session_state.last_query)
# Sliders for customization
col1, col2 = st.columns(2)
with col1:
top_k = st.slider("Number of sources:", 3, 10, 5)
with col2:
word_limit = st.slider("Word limit:", 50, 500, 200)
# Process button
if st.button("Get Answer") or st.session_state.submit_clicked:
if st.session_state.last_query:
# Reset the submit flag
st.session_state.submit_clicked = False
# Single processing spinner for the entire operation
with st.spinner("Processing your question..."):
try:
result = process_query(st.session_state.last_query, top_k=top_k, word_limit=word_limit)
st.subheader("Answer:")
st.write(result["answer_with_rag"])
st.subheader("Sources:")
for citation in result["citations"].split("\n"):
st.write(citation)
except Exception as e:
st.error(f"Error processing query: {str(e)}")
else:
st.warning("Please enter a question first.")
# Add helpful information
st.markdown("---")
st.markdown("""
### About this app
This application uses a Retrieval-Augmented Generation (RAG) system to answer questions about Indian spiritual texts.
It searches through a database of texts to find relevant passages and generates answers based on those passages.
""")