Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456783 unmodified lines121314151617181920212223242526272829303132333435363738394041424312 unmodified lines565758596061624 unmodified lines676869707172739 unmodified lines8384858687888990919293949596971 unmodified line991001011021031041051061071081091101111121132 unmodified lines1161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551563 unmodified lines1601611621631641651661671681691701711721731 unmodified line1751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162174 unmodified lines2222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552563 unmodified lines2602612622632642652662672682692702712722732742752762772782792801 unmodified line282283284285286287288289290# ---- Standard libs ----import os, tempfile, shutil, uuidimport streamlit as stfrom dotenv import load_dotenvfrom datetime import datetime# ---- LangChain stack ----from langchain_groq import ChatGroq3 unmodified linesfrom langchain_community.document_loaders import UnstructuredFileLoaderfrom langchain.text_splitter import RecursiveCharacterTextSplitter# ---- Load .env ----load_dotenv()# ---- Session Management ----if "session_id" not in st.session_state:st.session_state.session_id = str(uuid.uuid4())def cleanup_session_data():session_path = f"./rag_db/{st.session_state.session_id}"if os.path.exists(session_path):try:shutil.rmtree(session_path)except Exception as e:print(f"β οΈ Could not delete {session_path}: {e}")# Optional cleanup on reloadif "cleaned_up" not in st.session_state:cleanup_session_data()st.session_state["cleaned_up"] = True# ---- Initialize RAG Chain ----@st.cache_resource(show_spinner=False)def init_rag_chain():embedding = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")vectordb = Chroma(persist_directory=f"./rag_db/{st.session_state.session_id}",embedding_function=embedding)llm = ChatGroq(12 unmodified linesdef ingest_pdf(file_bytes: bytes, file_name: str):embedding = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")vectordb = Chroma(persist_directory=f"./rag_db/{st.session_state.session_id}", # <-- Fix thisembedding_function=embedding)with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:4 unmodified linessplitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)chunks = splitter.split_documents(docs)if chunks: # Avoid empty errorvectordb.add_documents(chunks)vectordb.persist()9 unmodified lines# ------------- Custom CSS Styling -------------st.markdown("""<style>/* Remove padding and center content */.block-container {padding-top: 2rem;padding-bottom: 2rem;max-width: 800px;margin: auto;}/* Title styling */.title {font-size: 3rem;font-weight: bold;1 unmodified linetext-align: center;margin-bottom: 1.5rem;}/* Main container */.main-container {max-width: 800px;margin: 0 auto;padding: 1rem;}/* Chat history container */.chat-history {max-height: 450px;overflow-y: auto;2 unmodified linespadding: 1rem;border: 1px solid #DDD;margin-bottom: 1rem;min-height: 100px;}/* Message styling */.message-user {background-color: #DDF3FF;color: #000;padding: 0.8rem;border-radius: 12px;margin-bottom: 0.5rem;text-align: left;word-wrap: break-word;}.message-bot {background-color: #E3FFE1;color: #000;padding: 0.8rem;border-radius: 12px;margin-bottom: 0.5rem;text-align: left;word-wrap: break-word;}/* Input styling */.stTextInput > div > div > input {font-size: 1rem;padding: 0.75rem;border-radius: 8px;border: 1px solid #DDD;height: 48px;min-height: 48px;}/* Button styling */.stButton > button {border-radius: 8px;background-color: #4A90E2;3 unmodified linesfont-weight: bold;width: 100%;height: 48px;min-height: 48px;}.stButton > button:hover {background-color: #357ABD;}/* File uploader styling */.stFileUploader > div {padding: 1rem;border: 2px dashed #4A90E2;1 unmodified linetext-align: center;margin-bottom: 1rem;}/* Sidebar styling */.sidebar-logo {text-align: center;margin-bottom: 1rem;}/* Input row alignment */.input-row {display: flex;gap: 0.5rem;align-items: end;margin-top: 1rem;}/* Success message styling */.stSuccess {margin-bottom: 0.5rem;}/* File uploader spacing */.stFileUploader {margin-bottom: 0.5rem;}/* Empty chat message */.empty-chat {text-align: center;color: #888;font-style: italic;padding: 1rem;}/* Reduce spacing after upload */.upload-section {margin-bottom: 1rem;}</style>""", unsafe_allow_html=True)4 unmodified linesst.write("β’ Upload a PDF π")st.write("β’ Ask context-specific questions π¬")st.write("β’ Powered by **LLaMA 3 + Groq** β‘")st.markdown("---")if st.button("ποΈ Clear Chat", use_container_width=True):cleanup_session_data() # <--- add this linest.session_state.chat_history = []st.rerun()# ------------- Main Content -------------# Titlest.markdown("<div class='title'>π Multimodal Chat Assistant</div>", unsafe_allow_html=True)# Main containerst.markdown("<div class='main-container'>", unsafe_allow_html=True)# Upload UIwith st.container():uploaded_file = st.file_uploader("π€ Upload a PDF file", type=["pdf"])if uploaded_file:with st.spinner("π Ingesting document..."):ingest_pdf(uploaded_file.read(), uploaded_file.name)st.success("β Document ingested successfully! You can now ask questions about the document.")# Initialize chat history if not presentif "chat_history" not in st.session_state:st.session_state.chat_history = []# Display chat historyif st.session_state.chat_history:st.markdown("<div class='chat-history'>", unsafe_allow_html=True)for msg in st.session_state.chat_history:3 unmodified linesst.markdown(f"<div class='message-bot'><b>π€ Assistant:</b> {msg['content']}</div>", unsafe_allow_html=True)st.markdown("</div>", unsafe_allow_html=True)# Input section with proper alignmentcol1, col2 = st.columns([5, 1])with col1:prompt = st.text_input("π¬ Type your question", placeholder="Ask something about your PDF...", label_visibility="collapsed")with col2:send_clicked = st.button("Send β‘οΈ", use_container_width=True)# Handle input and responseif (prompt and send_clicked) or (prompt and st.session_state.get('last_prompt', '') != prompt):if prompt.strip(): # Only process non-empty prompts# Add user messagest.session_state.chat_history.append({"role": "user", "content": prompt})# Get responsewith st.spinner("π€ Thinking..."):try:response = qa_chain.run(prompt)1 unmodified lineexcept Exception as e:error_msg = f"Sorry, I encountered an error: {str(e)}"st.session_state.chat_history.append({"role": "assistant", "content": error_msg})# Store last prompt to avoid duplicatesst.session_state.last_prompt = promptst.rerun()st.markdown("</div>", unsafe_allow_html=True)1234567893 unmodified lines13141516171819202122232425262728293031323312 unmodified lines464748495051524 unmodified lines575859606162639 unmodified lines7374757677787980818283841 unmodified line8687888990912 unmodified lines9495969798991001011021031041051061071081091101111121131141151161171181191201211221233 unmodified lines1271281291301311321331341351361 unmodified line1381391401411421431441451461474 unmodified lines1521531541551561571581591601611621631641651661671681691701711721731741751761771783 unmodified lines1821831841851861871881891901911921931941951961971 unmodified line199200201202203204# ---- Standard libs ----import os, tempfile, uuidimport streamlit as stfrom dotenv import load_dotenvfrom datetime import datetimefrom pathlib import Path# ---- LangChain stack ----from langchain_groq import ChatGroq3 unmodified linesfrom langchain_community.document_loaders import UnstructuredFileLoaderfrom langchain.text_splitter import RecursiveCharacterTextSplitter# ---- Load environment variables ----load_dotenv()# ---- Session-specific folder for vector store ----if "session_id" not in st.session_state:st.session_state.session_id = str(uuid.uuid4())persist_directory = os.path.join(tempfile.gettempdir(), f"rag_db_{st.session_state.session_id}")# ---- Initialize RAG Chain ----@st.cache_resource(show_spinner=False)def init_rag_chain():embedding = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")vectordb = Chroma(persist_directory=persist_directory,embedding_function=embedding)llm = ChatGroq(12 unmodified linesdef ingest_pdf(file_bytes: bytes, file_name: str):embedding = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")vectordb = Chroma(persist_directory=persist_directory,embedding_function=embedding)with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:4 unmodified linessplitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)chunks = splitter.split_documents(docs)if chunks:vectordb.add_documents(chunks)vectordb.persist()9 unmodified lines# ------------- Custom CSS Styling -------------st.markdown("""<style>.block-container {padding-top: 2rem;padding-bottom: 2rem;max-width: 800px;margin: auto;}.title {font-size: 3rem;font-weight: bold;1 unmodified linetext-align: center;margin-bottom: 1.5rem;}.chat-history {max-height: 450px;overflow-y: auto;2 unmodified linespadding: 1rem;border: 1px solid #DDD;margin-bottom: 1rem;}.message-user {background-color: #DDF3FF;padding: 0.8rem;border-radius: 12px;margin-bottom: 0.5rem;text-align: left;word-wrap: break-word;}.message-bot {background-color: #E3FFE1;padding: 0.8rem;border-radius: 12px;margin-bottom: 0.5rem;text-align: left;word-wrap: break-word;}.stTextInput > div > div > input {font-size: 1rem;padding: 0.75rem;border-radius: 8px;border: 1px solid #DDD;height: 48px;}.stButton > button {border-radius: 8px;background-color: #4A90E2;3 unmodified linesfont-weight: bold;width: 100%;height: 48px;}.stButton > button:hover {background-color: #357ABD;}.stFileUploader > div {padding: 1rem;border: 2px dashed #4A90E2;1 unmodified linetext-align: center;margin-bottom: 1rem;}.sidebar-logo {text-align: center;margin-bottom: 1rem;}</style>""", unsafe_allow_html=True)4 unmodified linesst.write("β’ Upload a PDF π")st.write("β’ Ask context-specific questions π¬")st.write("β’ Powered by **LLaMA 3 + Groq** β‘")st.markdown("---")if st.button("ποΈ Clear Chat"):st.session_state.chat_history = []Path(persist_directory).mkdir(parents=True, exist_ok=True)for f in Path(persist_directory).glob("*"):f.unlink()st.rerun()# ------------- Main Content -------------st.markdown("<div class='title'>π Multimodal Chat Assistant</div>", unsafe_allow_html=True)uploaded_file = st.file_uploader("π€ Upload a PDF file", type=["pdf"])if uploaded_file:with st.spinner("π Ingesting document..."):ingest_pdf(uploaded_file.read(), uploaded_file.name)st.success("β Document ingested. Ask away!")if "chat_history" not in st.session_state:st.session_state.chat_history = []if st.session_state.chat_history:st.markdown("<div class='chat-history'>", unsafe_allow_html=True)for msg in st.session_state.chat_history:3 unmodified linesst.markdown(f"<div class='message-bot'><b>π€ Assistant:</b> {msg['content']}</div>", unsafe_allow_html=True)st.markdown("</div>", unsafe_allow_html=True)col1, col2 = st.columns([5, 1])with col1:prompt = st.text_input("π¬ Type your question", placeholder="Ask something about your PDF...", label_visibility="collapsed")with col2:send_clicked = st.button("Send β‘οΈ")if (prompt and send_clicked) or (prompt and st.session_state.get('last_prompt', '') != prompt):if prompt.strip():st.session_state.chat_history.append({"role": "user", "content": prompt})with st.spinner("π€ Thinking..."):try:response = qa_chain.run(prompt)1 unmodified lineexcept Exception as e:error_msg = f"Sorry, I encountered an error: {str(e)}"st.session_state.chat_history.append({"role": "assistant", "content": error_msg})st.session_state.last_prompt = promptst.rerun()
app.py+21-107