Spaces:
Configuration error
Configuration error
Update src/streamlit_app.py
Browse files3 unmodified lines45678910111213141516171 unmodified line1920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402413 unmodified lines# --- 1. PAGE CONFIGURATION ---st.set_page_config(page_title="The Voice of the Sign",page_icon="π¦ ",layout="wide",initial_sidebar_state="expanded")# --- 2. BACKEND LOADING ---# We try to import the brain. If it fails, we show a pretty error.backend_loaded = Falsetry:from app import get_rag_chain, search_archives1 unmodified lineexcept ImportError as e:st.error(f"β System Error: Could not load the Brain.\n\nDetails: {e}")# --- 3. CUSTOM CSS (The "Appealing" Look) ---st.markdown("""<style>/* IMPORT FONTS */@import url('https://fonts.googleapis.com/css2?family=Merriweather:ital,wght@0,300;0,400;0,700;1,300&family=Inter:wght@300;400;600&display=swap');/* GLOBAL THEME */.stApp {background-color: #FDFBF7; /* Parchment White */}h1, h2, h3 {font-family: 'Merriweather', serif !important;color: #2C3E50;}p, div, label {font-family: 'Inter', sans-serif;color: #34495E;}/* CHAT BUBBLES - USER */div[data-testid="stChatMessage"][data-test-role="user"] {background-color: #EAECEE;border-radius: 20px 20px 5px 20px;padding: 15px;box-shadow: 0 2px 5px rgba(0,0,0,0.05);}/* CHAT BUBBLES - ASSISTANT */div[data-testid="stChatMessage"][data-test-role="assistant"] {background-color: #FFFFFF;border: 1px solid #D4AF37; /* Gold Border */border-radius: 20px 20px 20px 5px;padding: 20px;box-shadow: 0 4px 10px rgba(0,0,0,0.05);}/* AVATARS */.stChatMessage .stChatMessageAvatar {background-color: #2C3E50 !important; /* Navy Blue */color: white !important;}/* QUOTE CARDS (SEARCH MODE) */.quote-card {background-color: #FFFFFF;border-left: 6px solid #D4AF37; /* Gold Accent */padding: 20px;margin-bottom: 20px;border-radius: 8px;box-shadow: 0 4px 6px rgba(0,0,0,0.05);transition: transform 0.2s;}.quote-card:hover {transform: translateY(-2px);box-shadow: 0 8px 15px rgba(0,0,0,0.1);}.quote-meta {font-family: 'Inter', sans-serif;font-size: 0.85rem;color: #7F8C8D;text-transform: uppercase;letter-spacing: 1px;margin-bottom: 8px;font-weight: 600;}.quote-text {font-family: 'Merriweather', serif;font-size: 1.05rem;line-height: 1.6;color: #2C3E50;}/* SIDEBAR STYLING */section[data-testid="stSidebar"] {background-color: #F4F6F7;border-right: 1px solid #E5E7E9;}/* INPUT BOX */.stChatInput textarea {border-radius: 15px !important;border: 1px solid #BDC3C7 !important;}</style>""", unsafe_allow_html=True)# --- 4. SESSION STATE INITIALIZATION (Fixes the "Clearing" Issue) ---if "messages" not in st.session_state:st.session_state.messages = []# --- 5. SIDEBAR CONTROLS ---with st.sidebar:st.markdown("### π¦ Controls")mode = st.radio("Select Mode:",["π£οΈ Chat with Bro. Branham", "π Search Quotes Only"],captions=["Ask theological questions.", "Find exact paragraphs."],index=0)st.markdown("---")# CLEAR BUTTON (Resets Memory)if st.button("ποΈ Clear Conversation", use_container_width=True):st.session_state.messages = []st.rerun()st.markdown("---")st.info("π‘ **Tip:** Ask specific questions like *'What is the Third Pull?'* .")# --- 6. MAIN HEADER ---col1, col2 = st.columns([1, 6])with col1:st.markdown("# π¦ ") # Simple Iconwith col2:if mode.startswith("π£οΈ"):st.markdown("# The 7th Handle\n*Interactive AI Archive*")else:st.markdown("# The Table\n*Direct Quote Search*")st.divider()if not backend_loaded: st.stop()# --- 7. LOAD SYSTEM (Cached) ---@st.cache_resource(show_spinner=False)def load_system():return get_rag_chain()# --- 8. DISPLAY CHAT HISTORY (Persistent) ---# This block ensures old messages stay on screenfor message in st.session_state.messages:# We differentiate between "Search Results" and "Chat Messages" visuallyif message["role"] == "user":with st.chat_message("user", avatar="π€"):st.markdown(message["content"])elif message["role"] == "assistant":with st.chat_message("assistant", avatar="π¦ "):st.markdown(message["content"])# If sources exist, show them in a dropdownif "sources" in message and message["sources"]:with st.expander("π View Sermon References"):for src in message["sources"]:st.markdown(f"- *{src}*")# --- 9. INPUT HANDLER ---prompt = st.chat_input("Ask a question or search...")if prompt:# 9a. SHOW USER MESSAGE IMMEDIATELYst.session_state.messages.append({"role": "user", "content": prompt})with st.chat_message("user", avatar="π€"):st.markdown(prompt)# 9b. PROCESS BASED ON MODE# === CHAT MODE ===if mode.startswith("π£οΈ"):with st.chat_message("assistant", avatar="π¦ "):message_placeholder = st.empty()full_response = ""with st.spinner("Searching the archives..."):try:chain = load_system()response = chain.invoke({"question": prompt})result_text = response['result']source_docs = response.get('source_documents', [])unique_sources = list(set([doc.metadata.get('source', 'Unknown Tape') for doc in source_docs]))# TYPEWRITER EFFECTfor chunk in result_text.split():full_response += chunk + " "time.sleep(0.02) # Subtle typing speedmessage_placeholder.markdown(full_response + "β")message_placeholder.markdown(full_response)# SHOW SOURCESif unique_sources:with st.expander("π Sermon References"):for src in unique_sources: st.markdown(f"- *{src}*")# SAVE TO HISTORYst.session_state.messages.append({"role": "assistant","content": full_response,"sources": unique_sources})except Exception as e:st.error(f"Error: {e}")# === SEARCH MODE ===else:# For Search Mode, we don't save to chat history the same way.# We just display the results clearly.st.markdown(f"### π Results for: *'{prompt}'*")with st.spinner("Scanning local and cloud libraries..."):docs, debug_log = search_archives(prompt)# DIAGNOSTICS (Collapsible)with st.expander("π οΈ View System Diagnostics", expanded=False):for line in debug_log: st.write(line)if not docs:st.warning("No relevant records found.")else:for doc in docs:src = doc.metadata.get('source', 'Tape')para = doc.metadata.get('paragraph', '')# Highlight the keywordtxt = doc.page_content.replace(prompt, f"**{prompt}**")st.markdown(f"""<div class="quote-card">3 unmodified lines456789101112131415161 unmodified line181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891903 unmodified lines# --- 1. PAGE CONFIGURATION ---st.set_page_config(page_title="Voice of the Sign",page_icon="π¦ ",layout="wide",initial_sidebar_state="expanded")# --- 2. BACKEND LOADING ---backend_loaded = Falsetry:from app import get_rag_chain, search_archives1 unmodified lineexcept ImportError as e:st.error(f"β System Error: Could not load the Brain.\n\nDetails: {e}")# --- 3. ADAPTIVE CSS ---st.markdown("""<style>/* FONTS & BASICS */@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&family=Playfair+Display:ital,wght@0,600;1,600&display=swap');html, body, [class*="css"] { font-family: 'Inter', sans-serif; }h1, h2, h3 { font-family: 'Playfair Display', serif !important; }/* CHAT BUBBLES */div[data-testid="stChatMessage"][data-test-role="user"] {background-color: rgba(128, 128, 128, 0.1);border-radius: 20px 20px 5px 20px;}div[data-testid="stChatMessage"][data-test-role="assistant"] {background-color: rgba(212, 175, 55, 0.05);border-radius: 20px 20px 20px 5px;border-left: 4px solid #D4AF37;}/* QUOTE CARDS (SEARCH) */.quote-card {padding: 20px;margin-bottom: 15px;border-radius: 12px;border-left: 5px solid #D4AF37;transition: transform 0.2s;}.quote-meta {font-size: 0.85rem;text-transform: uppercase;letter-spacing: 1px;opacity: 0.7;margin-bottom: 8px;font-weight: 600;}.quote-text {font-family: 'Playfair Display', serif;font-size: 1.1rem;line-height: 1.6;font-style: italic;}/* DARK/LIGHT ADAPTATION */@media (prefers-color-scheme: dark) {.quote-card { background-color: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1); }.quote-text { color: #E0E0E0; }.quote-meta { color: #D4AF37; }}@media (prefers-color-scheme: light) {.quote-card { background-color: #FFFFFF; border: 1px solid #E0E0E0; box-shadow: 0 4px 6px rgba(0,0,0,0.05); }.quote-text { color: #2C3E50; }.quote-meta { color: #7F8C8D; }}header {visibility: hidden;}#MainMenu {visibility: hidden;}</style>""", unsafe_allow_html=True)# --- 4. SESSION STATE ---# We store messages ONLY for the Chat Modeif "chat_history" not in st.session_state:st.session_state.chat_history = []# --- 5. SIDEBAR ---with st.sidebar:st.title("π¦ Controls")mode = st.radio("Mode:", ["π£οΈ Chat", "π Search"], index=0, label_visibility="collapsed")st.divider()# Clear button acts differently depending on modeif st.button("ποΈ Clear Screen", use_container_width=True):if mode.startswith("π£οΈ"):st.session_state.chat_history = []# For search, rerunning effectively clears the transient resultst.rerun()# --- 6. HEADER ---col1, col2 = st.columns([1, 15])with col1: st.markdown("# π¦ ")with col2:if mode.startswith("π£οΈ"):st.markdown("# The 7th Handle")else:st.markdown("# The Table")st.divider()if not backend_loaded: st.stop()# --- 7. LOAD SYSTEM ---@st.cache_resource(show_spinner=False)def load_system():return get_rag_chain()# --- 8. MAIN LOGIC ---# === A. CHAT MODE (Has Memory) ===if mode.startswith("π£οΈ"):# 1. Display Historyfor message in st.session_state.chat_history:role = message["role"]with st.chat_message(role, avatar="π€" if role == "user" else "π¦ "):st.markdown(message["content"])if "sources" in message and message["sources"]:with st.expander("π References"):for src in message["sources"]: st.markdown(f"- `{src}`")# 2. Handle Inputif prompt := st.chat_input("Ask a question..."):# Save User Msgst.session_state.chat_history.append({"role": "user", "content": prompt})with st.chat_message("user", avatar="π€"):st.markdown(prompt)# Generate Replywith st.chat_message("assistant", avatar="π¦ "):placeholder = st.empty()full_response = ""with st.spinner("Thinking..."):try:chain = load_system()response = chain.invoke({"question": prompt})result_text = response['result']for chunk in result_text.split():full_response += chunk + " "time.sleep(0.02)placeholder.markdown(full_response + "β")placeholder.markdown(full_response)source_docs = response.get('source_documents', [])unique_sources = list(set([doc.metadata.get('source', 'Unknown') for doc in source_docs]))if unique_sources:with st.expander("π References"):for src in unique_sources: st.markdown(f"- `{src}`")# Save Assistant Msgst.session_state.chat_history.append({"role": "assistant","content": full_response,"sources": unique_sources})except Exception as e:st.error(f"Error: {e}")# === B. SEARCH MODE (No Memory - Instant Results) ===else:# Notice: We do NOT loop through history here.# The screen is fresh every time.if prompt := st.chat_input("Search for a keyword (e.g. 'Coleman')..."):st.subheader(f"Results for: '{prompt}'")with st.spinner("Scanning archives..."):docs, debug_log = search_archives(prompt)with st.expander("π οΈ Debug Info", expanded=False):for line in debug_log: st.write(line)if not docs:st.info("No exact records found.")else:for doc in docs:src = doc.metadata.get('source', 'Tape')para = doc.metadata.get('paragraph', '')txt = doc.page_content.replace(prompt, f"**{prompt}**") # Highlightst.markdown(f"""<div class="quote-card">
src/streamlit_app.py+90-141