Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940import altair as altimport numpy as npimport pandas as pdimport streamlit as st"""# Welcome to Streamlit!Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).In the meantime, below is an example of what you can do with just a few lines of code:"""num_points = st.slider("Number of points in spiral", 1, 10000, 1100)num_turns = st.slider("Number of turns in spiral", 1, 300, 31)indices = np.linspace(0, 1, num_points)theta = 2 * np.pi * num_turns * indicesradius = indicesx = radius * np.cos(theta)y = radius * np.sin(theta)df = pd.DataFrame({"x": x,"y": y,"idx": indices,"rand": np.random.randn(num_points),})st.altair_chart(alt.Chart(df, height=700, width=700).mark_point(filled=True).encode(x=alt.X("x", axis=None),y=alt.Y("y", axis=None),color=alt.Color("idx", legend=None, scale=alt.Scale()),size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217import streamlit as stimport requestsimport os# Backend URL (change if deployed)BACKEND_URL = "http://localhost:8000"st.set_page_config(page_title="PDF Assistant", page_icon="π", layout="wide")# ---------------- CSS (Dark Theme) ----------------# FIX: Added CSS for the footerst.markdown("""<style>/* Streamlit standard setup for dark theme adherence */:root {--primary-color: #1e3a8a; /* Blue for highlights */--background-color: #0e1117;--secondary-background-color: #1a1d29;--text-color: #f0f2f6;}/* Custom Chat Bubbles */.chat-user {background: #2d3748; /* Dark gray */padding: 12px;border-radius: 10px 10px 2px 10px; /* Rounded corners for chat bubble */margin: 6px 0 6px auto;max-width: 85%;text-align: right;color: var(--text-color);}.chat-bot {background: var(--primary-color); /* Primary blue */padding: 12px;border-radius: 10px 10px 10px 2px;margin: 6px auto 6px 0;max-width: 85%;text-align: left;color: #ffffff; /* White text for contrast */}/* Sources section styling */.sources {font-size: 0.8em;opacity: 0.7;margin-top: 10px;border-top: 1px solid rgba(255, 255, 255, 0.1);padding-top: 5px;}/* Footer styling */.footer {position: fixed;left: 0;bottom: 0;width: 100%;background-color: var(--secondary-background-color);color: var(--text-color);text-align: center;padding: 10px;font-size: 0.85em;border-top: 1px solid rgba(255, 255, 255, 0.1);}.footer a {color: var(--primary-color);text-decoration: none;font-weight: bold;}.footer a:hover {text-decoration: underline;}</style>""", unsafe_allow_html=True)# ---------------- SESSION STATE ----------------if "chat" not in st.session_state:st.session_state.chat = []if "uploaded_file_name" not in st.session_state:st.session_state.uploaded_file_name = None# Add a key to the file uploader to allow it to be reset.if "uploader_key" not in st.session_state:st.session_state.uploader_key = 0# FIX 1: Change application namest.title("π PDF Assistant")# ---------------- FUNCTIONS ----------------def clear_chat_history():"""Clears the chat history in the session state."""st.session_state.chat = []def clear_memory():"""Calls the backend endpoint to clear loaded PDF data and resets UI state."""res = requests.post(f"{BACKEND_URL}/clear")if res.status_code == 200:st.session_state.uploaded_file_name = None# Increment the key of the file uploader to clear its valuest.session_state.uploader_key += 1st.success("Memory cleared. Please upload a new PDF.")else:st.error(f"Failed to clear memory: {res.json().get('detail', 'Unknown error')}")# Removed st.rerun() to prevent "no-op" warning# ---------------- SIDEBAR CONTROLS ----------------with st.sidebar:st.header("Controls")st.button("ποΈ Clear Chat History", on_click=clear_chat_history, use_container_width=True)st.button("π₯ Clear PDF Memory", on_click=clear_memory, use_container_width=True)st.markdown("---")if st.session_state.uploaded_file_name:st.success(f"β **Active PDF:**\n `{st.session_state.uploaded_file_name}`")else:st.warning("β¬οΈ Upload a PDF to start chatting!")# ---------------- UPLOAD PDF ----------------# Use the dynamic key for the file uploader.uploaded = st.file_uploader("Upload your PDF",type=["pdf"],key=st.session_state.uploader_key # Use the dynamic key)# Only process if a file is uploaded AND it's a NEW fileif uploaded and uploaded.name != st.session_state.uploaded_file_name:st.session_state.uploaded_file_name = None # Clear status while processingst.session_state.chat = [] # Clear chat for a new documentwith st.spinner(f"Processing '{uploaded.name}'..."):try:files = {"file": (uploaded.name, uploaded.getvalue(), "application/pdf")}res = requests.post(f"{BACKEND_URL}/upload", files=files)if res.status_code == 200:chunks = res.json().get("chunks", 0)st.success(f"PDF processed successfully! {chunks} chunks created.")st.session_state.uploaded_file_name = uploaded.nameelse:error_msg = res.json().get("detail", "Unknown error during processing.")st.error(f"Upload failed: {error_msg}")st.session_state.uploaded_file_name = Noneexcept requests.exceptions.ConnectionError:st.error(f"Could not connect to the backend server at {BACKEND_URL}. Ensure it is running.")st.session_state.uploaded_file_name = Noneexcept Exception as e:st.error(f"An unexpected error occurred: {e}")st.session_state.uploaded_file_name = None# Rerun the app to update the UI status immediatelyst.rerun()# ---------------- CHAT INPUT ----------------# Disable input field if no PDF is loadeddisabled_input = st.session_state.uploaded_file_name is Nonequestion = st.text_input("Ask a question about the loaded PDF:",key="question_input",disabled=disabled_input)if st.button("Send", disabled=disabled_input) and question:# 1. Add user query to chat historyst.session_state.chat.append(("user", question))# 2. Call backendwith st.spinner("Thinking..."):try:res = requests.post(f"{BACKEND_URL}/ask", json={"question": question})if res.status_code == 200:data = res.json()answer = data.get("answer", "No answer provided.")sources = data.get("sources", 0)# Format the bot's response to include source countbot_message = f"{answer}<div class='sources'>Context Chunks Used: {sources}</div>"st.session_state.chat.append(("bot", bot_message))else:error_detail = res.json().get("detail", "Error while generating answer.")st.session_state.chat.append(("bot", f"π΄ **Error:** {error_detail}"))except requests.exceptions.ConnectionError:st.session_state.chat.append(("bot",f"π΄ **Error:** Could not connect to the backend server at {BACKEND_URL}. Ensure it is running."))except Exception as e:st.session_state.chat.append(("bot", f"π΄ **An unexpected error occurred:** {e}"))# Rerun to display the updated chat historyst.rerun()# ---------------- SHOW CHAT HISTORY ----------------st.markdown("## Chat History")# Reverse the list to show the latest messages at the bottomfor role, msg in st.session_state.chat:if role == "user":st.markdown(f"<div class='chat-user'>{msg}</div>", unsafe_allow_html=True)else:# Bot message includes the source count, so use the HTML contentst.markdown(f"<div class='chat-bot'>{msg}</div>", unsafe_allow_html=True)# ---------------- FOOTER (Creator Credit) ----------------# FIX 2: Add creator credit with LinkedIn linkfooter_html = """<div class="footer">Created by <a href="https://www.linkedin.com/in/abhishek-iitr/" target="_blank">Abhishek Saxena</a></div>"""st.markdown(footer_html, unsafe_allow_html=True)# ---------------- END ----------------
src/streamlit_app.py+211-34