Spaces:
Configuration error
Configuration error
Update src/streamlit_app.py
Browse files1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211 unmodified lineimport timeimport os# Import backend logictry:from app import get_rag_chainexcept ImportError as e:st.error(f"CRITICAL ERROR: {e}")st.stop()# --- PAGE CONFIG ---st.set_page_config(page_title="Voice of the Sign", page_icon="π¦ ", layout="centered")# --- CSS STYLING (Dark Mode Fix) ---st.markdown("""<style>/* Force chat bubbles to look correct regardless of user theme */div[data-testid="stChatMessage"] {background-color: #ffffff !important;border: 1px solid #e0e0e0;color: #000000 !important;}/* Ensure text inside bubbles is black */div[data-testid="stChatMessage"] p,div[data-testid="stChatMessage"] li {color: #000000 !important;}/* Hide default footer */footer {visibility: hidden;}</style>""", unsafe_allow_html=True)# --- INITIALIZE CHAT ---if "messages" not in st.session_state:st.session_state.messages = [{"role": "assistant", "content": "God bless you. What is on your heart?"}]# --- LOAD BRAIN ---@st.cache_resource(show_spinner=False)def load_chain():return get_rag_chain()if "chain" not in st.session_state:with st.spinner("Connecting to the Message..."):try:st.session_state.chain = load_chain()except Exception as e:st.error(f"Connection Failed: {e}")st.stop()chain = st.session_state.chain# --- DISPLAY CHAT HISTORY ---st.title("π¦ The Message AI")st.caption("Interactive Archive β’ Powered by Pinecone & Gemini")st.divider()for msg in st.session_state.messages:with st.chat_message(msg["role"], avatar="π" if msg["role"] == "assistant" else "π€"):st.markdown(msg["content"])if "sources" in msg:with st.expander("π References"):for src in msg["sources"]:st.markdown(f"- {src}")# --- INPUT HANDLING ---if prompt := st.chat_input("Ask a question..."):st.session_state.messages.append({"role": "user", "content": prompt})with st.chat_message("user", avatar="π€"):st.markdown(prompt)with st.chat_message("assistant", avatar="π"):with st.spinner("Searching..."):try:response = chain.invoke({"query": prompt})result = response['result']# --- SMART REFERENCE FORMATTER ---# This reads the metadata you uploaded to Pineconesources = []for doc in response.get('source_documents', []):meta = doc.metadata# Get fields (defaults if missing)source_file = meta.get('source', 'Unknown')para = meta.get('paragraph', 'Intro')title = meta.get('title', 'Unknown Title')date = meta.get('date', '')# Logic: Avoid repeating if Title IS the Dateif title == date:display_str = f"**{source_file}** | Para {para}"elif title != "Unknown Title":display_str = f"**{title}** ({date}) | Para {para}"else:display_str = f"**{source_file}** | Para {para}"sources.append(display_str)# Remove duplicatesunique_sources = list(dict.fromkeys(sources))# Display Responsest.markdown(result)# Save to Historyst.session_state.messages.append({"role": "assistant","content": result,"sources": unique_sources})if unique_sources:with st.expander("π References"):for src in unique_sources:st.markdown(f"- {src}")except Exception as e:st.error(f"Error: {e}")1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322331 unmodified lineimport 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)
src/streamlit_app.py+215-103