Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657587 unmodified lines666768697071727374757677787980818283137 unmodified lines221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297# ---- Standard libs ----import os, tempfilefrom datetime import datetime# ---- Streamlit ----import streamlit as st# ---- Load environment variables (.env) ----from dotenv import load_dotenvload_dotenv()# ---- LangChain + Groq stack ----from langchain_groq import ChatGroqfrom langchain_community.embeddings import HuggingFaceEmbeddingsfrom langchain_community.vectorstores import Chromafrom langchain.chains import RetrievalQAfrom langchain_community.document_loaders import UnstructuredFileLoaderfrom langchain.text_splitter import RecursiveCharacterTextSplitterimport uuidimport shutildef cleanup_session_data():"""Deletes the current session's vector store folder"""session_path = f"./rag_db/{st.session_state.session_id}"if os.path.exists(session_path):try:shutil.rmtree(session_path)print(f"β Deleted session data at: {session_path}")except Exception as e:print(f"β οΈ Failed to delete session data: {e}")# Generate a unique session ID per userif "session_id" not in st.session_state:st.session_state.session_id = str(uuid.uuid4())# Clean up previous session data on reload (optional)if "cleaned_up" not in st.session_state:cleanup_session_data()st.session_state["cleaned_up"] = True# ------------- Chain Initializer -------------@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(groq_api_key=os.getenv("GROQ_API_KEY"),model="llama3-70b-8192",7 unmodified linesqa_chain = init_rag_chain()# ------------- PDF Ingestion -------------def ingest_pdf(file_bytes: bytes, file_name: str):embedding = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")vectordb = Chroma(persist_directory="./rag_db", embedding_function=embedding)with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:tmp.write(file_bytes)tmp_path = tmp.namedocs = UnstructuredFileLoader(tmp_path).load()splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)vectordb.add_documents(splitter.split_documents(docs))vectordb.persist()# ------------- Streamlit Config -------------st.set_page_config(page_title="π Multimodal Chat Assistant",137 unmodified lines</style>""", unsafe_allow_html=True)# ------------- Sidebar -------------with st.sidebar:st.markdown("<div class='sidebar-logo'><img src='https://cdn-icons-png.flaticon.com/512/4712/4712027.png' width='100'></div>", unsafe_allow_html=True)st.title("π€ RAG Assistant")st.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() # β correct indentationst.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:if msg["role"] == "user":st.markdown(f"<div class='message-user'><b>π§ You:</b> {msg['content']}</div>", unsafe_allow_html=True)else:st.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)st.session_state.chat_history.append({"role": "assistant", "content": response})except 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)1234567891011121314151617181920212223242526272829303132333435363738394041424344457 unmodified lines5354555657585960616263646566676869707172737475767778137 unmodified lines216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277# ---- Standard libs ----import os, tempfile, shutil, uuidimport streamlit as stfrom dotenv import load_dotenvfrom datetime import datetime# ---- LangChain stack ----from langchain_groq import ChatGroqfrom langchain_community.embeddings import HuggingFaceEmbeddingsfrom langchain_community.vectorstores import Chromafrom langchain.chains import RetrievalQAfrom langchain_community.document_loaders import PyPDFLoaderfrom 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(groq_api_key=os.getenv("GROQ_API_KEY"),model="llama3-70b-8192",7 unmodified linesqa_chain = init_rag_chain()# ---- PDF Ingestion ----def ingest_pdf(file_bytes: bytes, file_name: str):with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:tmp.write(file_bytes)tmp_path = tmp.nameloader = PyPDFLoader(tmp_path)docs = loader.load()splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)chunks = splitter.split_documents(docs)embedding = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")vectordb = Chroma(persist_directory=f"./rag_db/{st.session_state.session_id}",embedding_function=embedding)vectordb.add_documents(chunks)vectordb.persist()# ------------- Streamlit Config -------------st.set_page_config(page_title="π Multimodal Chat Assistant",137 unmodified lines</style>""", unsafe_allow_html=True)# ---- Sidebar ----with st.sidebar:st.image("https://cdn-icons-png.flaticon.com/512/4712/4712027.png", width=100)st.title("π€ RAG Assistant")st.write("β’ Upload a PDF π")st.write("β’ Ask context-specific questions π¬")st.write("β’ Powered by **LLaMA 3 + Groq** β‘")if st.button("ποΈ Clear Chat", use_container_width=True):cleanup_session_data()st.session_state.chat_history = []st.rerun()# ------------- Main Content -------------# ---- Title ----st.title("π Multimodal Chat Assistant")# ---- PDF Upload ----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.")# ---- Chat Logic ----if "chat_history" not in st.session_state:st.session_state.chat_history = []# Display chat historyfor msg in st.session_state.chat_history:if msg["role"] == "user":st.markdown(f"<div class='message-user'><b>π§ You:</b> {msg['content']}</div>", unsafe_allow_html=True)else:st.markdown(f"<div class='message-bot'><b>π€ Assistant:</b> {msg['content']}</div>", unsafe_allow_html=True)# Input promptcol1, 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)# Process promptif (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)st.session_state.chat_history.append({"role": "assistant", "content": response})except Exception as e:st.session_state.chat_history.append({"role": "assistant", "content": f"β οΈ Error: {e}"})st.session_state.last_prompt = promptst.rerun()
app.py+55-75