Spaces:
Configuration error
Configuration error
Update src/streamlit_app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233import streamlit as stimport timeimport os# --- 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_archivesbackend_loaded = Trueexcept ImportError as e:st.error(f"β System Error: Could not load the Brain.\n\nDetails: {e}")# --- 3. HELPER: SMART LINK GENERATOR ---def generate_sermon_link(filename):"""Converts '65_1128M_Gods_Only_Provided_Place.PDF'into 'https://churchages.net/en/sermon/branham/65-1128m-gods-only-provided-place'"""if not filename: return "#"try:# 1. Remove file extensionclean_name = filename.replace(".PDF", "").replace(".pdf", "")# 2. Replace underscores with dashes (ChurchAges format)clean_name = clean_name.replace("_", "-")# 3. Lowercase everythingslug = clean_name.lower()# 4. Build URLreturn f"https://churchages.net/en/sermon/branham/{slug}"except:return "#"# --- 4. 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.9rem;margin-bottom: 8px;font-weight: 600;}.quote-meta a {text-decoration: none;color: #D4AF37 !important; /* Gold Link */}.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; }}@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; }}header {visibility: hidden;}#MainMenu {visibility: hidden;}</style>""", unsafe_allow_html=True)# --- 5. SESSION STATE ---if "chat_history" not in st.session_state:st.session_state.chat_history = []# --- 6. SIDEBAR ---with st.sidebar:st.title("π¦ Controls")mode = st.radio("Mode:", ["π£οΈ Chat", "π Search"], index=0, label_visibility="collapsed")st.divider()if st.button("ποΈ Clear Screen", use_container_width=True):if mode.startswith("π£οΈ"):st.session_state.chat_history = []st.rerun()# --- 7. 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()# --- 8. LOAD SYSTEM ---@st.cache_resource(show_spinner=False)def load_system():return get_rag_chain()# --- 9. MAIN LOGIC ---# === A. CHAT MODE ===if mode.startswith("π£οΈ"):# 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 doc in message["sources"]:# Handle both string filenames and document objectsif hasattr(doc, 'metadata'):fname = doc.metadata.get('source', 'Unknown')para = doc.metadata.get('paragraph', '')else:fname = str(doc)para = ""link = generate_sermon_link(fname)st.markdown(f"π [{fname} (Para {para})]({link})")# Handle Inputif prompt := st.chat_input("Ask a question..."):st.session_state.chat_history.append({"role": "user", "content": prompt})with st.chat_message("user", avatar="π€"):st.markdown(prompt)with 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)# Process Sourcessource_docs = response.get('source_documents', [])unique_docs = {}for doc in source_docs:src = doc.metadata.get('source', 'Unknown')if src not in unique_docs:unique_docs[src] = docfinal_sources = list(unique_docs.values())if final_sources:with st.expander("π References"):for doc in final_sources:fname = doc.metadata.get('source', 'Unknown')para = doc.metadata.get('paragraph', '')link = generate_sermon_link(fname)st.markdown(f"π [{fname} (Para {para})]({link})")st.session_state.chat_history.append({"role": "assistant","content": full_response,"sources": final_sources})except Exception as e:st.error(f"Error: {e}")# === B. SEARCH MODE ===else:if prompt := st.chat_input("Search for a keyword..."):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}**")link = generate_sermon_link(src)# Render Card with Linkst.markdown(f"""<div class="quote-card"><div class="quote-meta"><a href="{link}" target="_blank">πΌ {src} (Para {para}) β</a></div><div class="quote-text">"{txt}"</div></div>""", unsafe_allow_html=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250import streamlit as stimport time# ==============================# PAGE CONFIG# ==============================st.set_page_config(page_title="Voice of the Sign",page_icon="π¦ ",layout="wide",initial_sidebar_state="expanded")# ==============================# LOAD BACKEND# ==============================backend_loaded = Falsetry:from app import get_rag_chain, search_archivesbackend_loaded = Trueexcept Exception as e:st.error(f"β Backend failed to load:\n\n{e}")# ==============================# MESSAGEHUB LINK BUILDER# ==============================def messagehub_link(filename: str):"""Example:62-0909E In His Presence.pdfβ https://www.messagehub.info/en/read.do?ref_num=62-0909E"""if not filename:return "#"name = filename.replace(".pdf", "").replace(".PDF", "").strip()code = name.split()[0] # first token is sermon codereturn f"https://www.messagehub.info/en/read.do?ref_num={code}"# ==============================# STYLING# ==============================st.markdown("""<style>@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&family=Playfair+Display:wght@600&display=swap');html, body, [class*="css"] {font-family: 'Inter', sans-serif;}h1, h2, h3 {font-family: 'Playfair Display', serif;}div[data-testid="stChatMessage"][data-test-role="user"] {background-color: rgba(128,128,128,0.08);border-radius: 20px 20px 5px 20px;}div[data-testid="stChatMessage"][data-test-role="assistant"] {background-color: rgba(212,175,55,0.05);border-left: 4px solid #D4AF37;border-radius: 20px 20px 20px 5px;}/* Improve markdown spacing */.markdown-text-container p {margin-bottom: 0.9em;line-height: 1.7;}.markdown-text-container ul {margin-left: 1.2em;}.markdown-text-container h3 {margin-top: 1.2em;color: #D4AF37;}/* Reference cards */.quote-card {padding: 18px;margin-bottom: 14px;border-radius: 12px;border-left: 5px solid #D4AF37;}.quote-meta {font-weight: 600;margin-bottom: 6px;}.quote-meta a {color: #D4AF37;text-decoration: none;}.quote-text {font-family: 'Playfair Display', serif;font-style: italic;line-height: 1.6;}@media (prefers-color-scheme: dark) {.quote-card {background-color: rgba(255,255,255,0.05);border: 1px solid rgba(255,255,255,0.08);}}@media (prefers-color-scheme: light) {.quote-card {background: #ffffff;border: 1px solid #e6e6e6;box-shadow: 0 4px 6px rgba(0,0,0,0.05);}}header, #MainMenu { visibility: hidden; }</style>""", unsafe_allow_html=True)# ==============================# SESSION STATE# ==============================if "chat_history" not in st.session_state:st.session_state.chat_history = []# ==============================# SIDEBAR# ==============================with st.sidebar:st.title("π¦ Controls")mode = st.radio("Mode", ["π£οΈ Chat", "π Search"], index=0, label_visibility="collapsed")st.divider()if st.button("ποΈ Clear Screen", use_container_width=True):st.session_state.chat_history = []st.rerun()# ==============================# HEADER# ==============================col1, col2 = st.columns([1, 14])with col1:st.markdown("# π¦ ")with col2:st.markdown("# The 7th Handle" if mode.startswith("π£οΈ") else "# The Table")st.divider()if not backend_loaded:st.stop()# ==============================# LOAD RAG SYSTEM# ==============================@st.cache_resource(show_spinner=False)def load_chain():return get_rag_chain()# =========================================================# CHAT MODE# =========================================================if mode.startswith("π£οΈ"):# --- Render chat history ---for msg in st.session_state.chat_history:with st.chat_message(msg["role"], avatar="π€" if msg["role"] == "user" else "π¦ "):st.markdown(msg["content"], unsafe_allow_html=False)if msg.get("sources"):with st.expander("π References"):for doc in msg["sources"]:src = doc.metadata.get("source", "")para = doc.metadata.get("paragraph", "")link = messagehub_link(src)st.markdown(f"π [{src} (Para {para})]({link})")# --- Input ---prompt = st.chat_input("Ask a question...")if prompt:# Save user messagest.session_state.chat_history.append({"role": "user","content": prompt})with st.spinner("Searching the tapes..."):chain = load_chain()response = chain.invoke({"question": prompt})answer_text = response.get("result", "")sources = response.get("source_documents", [])# Save assistant message (FULLY formed)st.session_state.chat_history.append({"role": "assistant","content": answer_text,"sources": sources})# Force rerender so references appear immediatelyst.rerun()# =========================================================# SEARCH MODE# =========================================================else:query = st.chat_input("Search for a keyword...")if query:st.subheader(f"Results for: β{query}β")with st.spinner("Scanning archives..."):docs, debug_log = search_archives(query)with st.expander("π Debug Info"):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", "")para = doc.metadata.get("paragraph", "")link = messagehub_link(src)st.markdown(f"""<div class="quote-card"><div class="quote-meta"><a href="{link}" target="_blank">πΌ {src} (Para {para})</a></div><div class="quote-text">"{doc.page_content}"</div></div>""", unsafe_allow_html=True)
src/streamlit_app.py+202-185