Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223146 unmodified lines170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463# ---- Standard libs ----import os, tempfilefrom datetime import datetimeimport json# ---- Streamlit ----import streamlit as st# ---- Load environment variables (.env) ----from dotenv import load_dotenvload_dotenv()# ---- RAG + Groq stack ----from langchain_groq import ChatGroqfrom langchain.embeddings import HuggingFaceEmbeddingsfrom langchain_community.vectorstores import Chromafrom langchain.chains import RetrievalQAfrom langchain_community.document_loaders import PyPDFLoaderfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_chroma import Chroma# ------------- Configuration -------------st.set_page_config(page_title="📄 Multimodal Chat Assistant",146 unmodified linesmargin-bottom: 2rem;}</style>""", unsafe_allow_html=True)# ------------- One‑time chain initializer -------------@st.cache_resource(show_spinner=False)def init_rag_chain(model_name="llama3-70b-8192", temperature=0.2):embedding = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")vectordb = Chroma(persist_directory="./rag_db",embedding_function=embedding,collection_metadata={"hnsw:space": "cosine"})llm = ChatGroq(groq_api_key=os.getenv("GROQ_API_KEY"),model=model_name,temperature=temperature,)return RetrievalQA.from_chain_type(llm=llm,retriever=vectordb.as_retriever(search_kwargs={"k": 4}),return_source_documents=False)# ------------- Document ingestion -------------# updated import ✅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,collection_metadata={"hnsw:space": "cosine"})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)os.unlink(tmp_path)if not chunks:st.error("❌ No text chunks extracted from the PDF.")return 0# Remove empty chunksnon_empty_chunks = [chunk for chunk in chunks if chunk.page_content.strip()]if not non_empty_chunks:st.error("❌ All extracted chunks are empty. Check your PDF content.")return 0vectordb.add_documents(non_empty_chunks)vectordb.persist()if "documents" not in st.session_state:st.session_state.documents = []st.session_state.documents.append({"name": file_name,"chunks": len(non_empty_chunks),"uploaded_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})return len(non_empty_chunks)# ------------- Initialize session state -------------if "chat_history" not in st.session_state:st.session_state.chat_history = []if "documents" not in st.session_state:st.session_state.documents = []if "total_questions" not in st.session_state:st.session_state.total_questions = 0# ------------- Sidebar Configuration -------------with st.sidebar:st.markdown("### ⚙️ Configuration")# Model selectionmodel_options = {"Llama 3 70B": "llama3-70b-8192","Llama 3 8B": "llama3-8b-8192","Mixtral 8x7B": "mixtral-8x7b-32768","Gemma 7B": "gemma-7b-it"}selected_model = st.selectbox("🤖 Select Model",options=list(model_options.keys()),index=0)temperature = st.slider("🌡️ Temperature",min_value=0.0,max_value=1.0,value=0.2,step=0.1,help="Higher values make output more creative")# Document statisticsst.markdown("### 📊 Statistics")col1, col2 = st.columns(2)with col1:st.markdown(f"""<div class="stats-card"><h4>📄 Documents</h4><h2>{len(st.session_state.documents)}</h2></div>""", unsafe_allow_html=True)with col2:st.markdown(f"""<div class="stats-card"><h4>💬 Questions</h4><h2>{st.session_state.total_questions}</h2></div>""", unsafe_allow_html=True)# Document listif st.session_state.documents:st.markdown("### 📚 Uploaded Documents")for doc in st.session_state.documents:st.markdown(f"""<div class="feature-card"><strong>{doc['name']}</strong><br><small>📄 {doc['chunks']} chunks</small><br><small>🕒 {doc['uploaded_at']}</small></div>""", unsafe_allow_html=True)# Clear chat buttonif st.button("🗑️ Clear Chat History", use_container_width=True):st.session_state.chat_history = []st.rerun()# ------------- Main Interface -------------st.markdown('<h1 class="premium-title">🤖 Multimodal Chat Assistant</h1>', unsafe_allow_html=True)st.markdown('<p class="subtitle">Upload your documents and chat with AI-powered intelligence</p>', unsafe_allow_html=True)# Initialize QA chain with selected modelqa_chain = init_rag_chain(model_options[selected_model], temperature)# Upload sectioncol1, col2, col3 = st.columns([1, 2, 1])with col2:st.markdown('<div class="upload-area">', unsafe_allow_html=True)uploaded_file = st.file_uploader("📤 Upload a PDF file",type=["pdf"],help="Upload a PDF document to start chatting with it")st.markdown('</div>', unsafe_allow_html=True)if uploaded_file is not None:with st.spinner("📚 Processing document... This may take a moment."):progress_bar = st.progress(0)for i in range(100):progress_bar.progress(i + 1)chunks_count = ingest_pdf(uploaded_file.read(), uploaded_file.name)progress_bar.empty()st.success(f"✅ Document processed successfully! Created {chunks_count} chunks.")st.balloons()# Chat interfacest.markdown('<div class="chat-container">', unsafe_allow_html=True)# Suggested questionsif not st.session_state.chat_history and st.session_state.documents:st.markdown("### 💡 Suggested Questions")suggestions = ["📋 What is the main topic of this document?","🔍 Can you summarize the key points?","📊 What are the important statistics mentioned?","🎯 What conclusions does the document draw?"]cols = st.columns(2)for i, suggestion in enumerate(suggestions):with cols[i % 2]:if st.button(suggestion, key=f"suggestion_{i}", use_container_width=True):st.session_state.chat_history.append({"role": "user","content": suggestion.split(" ", 1)[1],"timestamp": datetime.now().strftime("%H:%M")})st.session_state.total_questions += 1st.rerun()# Chat inputprompt = st.text_input("💬 Ask a question about your document",placeholder="Type your question here...",key="chat_input")if prompt:# Add user messagest.session_state.chat_history.append({"role": "user","content": prompt,"timestamp": datetime.now().strftime("%H:%M")})st.session_state.total_questions += 1# Generate responsewith st.spinner("🤔 Thinking..."):try:response = qa_chain.run(prompt)st.session_state.chat_history.append({"role": "assistant","content": response,"timestamp": datetime.now().strftime("%H:%M")})except Exception as e:st.error(f"❌ Error: {str(e)}")st.rerun()# Display chat historyif st.session_state.chat_history:st.markdown("### 💬 Conversation")for i, msg in enumerate(st.session_state.chat_history):if msg["role"] == "user":st.markdown(f"""<div style="display: flex; justify-content: flex-end; margin: 1rem 0;"><div class="message-user"><strong>🧑 You</strong> <small style="opacity: 0.7;">({msg.get('timestamp', '')})</small><br>{msg['content']}</div></div>""", unsafe_allow_html=True)else:st.markdown(f"""<div style="display: flex; justify-content: flex-start; margin: 1rem 0;"><div class="message-bot"><strong>🤖 Assistant</strong> <small style="opacity: 0.7;">({msg.get('timestamp', '')})</small><br>{msg['content']}</div></div>""", unsafe_allow_html=True)# Add action buttons for bot responsescol1, col2, col3, col4 = st.columns([1, 1, 1, 5])with col1:if st.button("👍", key=f"like_{i}", help="Like this response"):st.toast("👍 Response liked!")with col2:if st.button("👎", key=f"dislike_{i}", help="Dislike this response"):st.toast("👎 Feedback noted!")with col3:if st.button("📋", key=f"copy_{i}", help="Copy response"):st.toast("📋 Response copied!")else:if not st.session_state.documents:st.markdown("""<div class="feature-card" style="text-align: center;"><h3>🚀 Get Started</h3><p>Upload a PDF document above to begin chatting with your AI assistant!</p><h4>✨ Features:</h4><ul style="text-align: left; display: inline-block;"><li>🤖 Multiple AI models to choose from</li><li>📄 Advanced document processing</li><li>💬 Interactive chat interface</li><li>📊 Real-time statistics</li><li>🎨 Premium UI/UX design</li></ul></div>""", unsafe_allow_html=True)st.markdown('</div>', unsafe_allow_html=True)# Footerst.markdown("""<div style="text-align: center; margin-top: 3rem; padding: 2rem; color: rgba(255,255,255,0.6);"><p>🤖 Powered by Groq AI • Built with ❤️ using Streamlit</p></div>""", unsafe_allow_html=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071146 unmodified lines218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249# ---- Standard libs ----import os, tempfilefrom datetime import datetime# ---- Streamlit ----import streamlit as st# ---- Load environment variables (.env) ----from dotenv import load_dotenvload_dotenv() # <-- makes GROQ_API_KEY available# ---- RAG + Groq stack ----from langchain_groq import ChatGroqfrom langchain.embeddings import HuggingFaceEmbeddingsfrom langchain_community.vectorstores import Chromafrom langchain.chains import RetrievalQAfrom langchain_community.document_loaders import UnstructuredFileLoaderfrom langchain.text_splitter import RecursiveCharacterTextSplitter# ------------- One‑time chain initialiser -------------@st.cache_resource(show_spinner=False)def init_rag_chain():# 1️⃣ Embeddingsembedding = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")# 2️⃣ Persisted vector DBvectordb = Chroma(persist_directory="./rag_db",embedding_function=embedding)llm = ChatGroq(groq_api_key=os.getenv("GROQ_API_KEY"), # <--- THIS is criticalmodel="llama3-70b-8192",temperature=0.2,)# 4️⃣ Retrieval‑augmented QA chainreturn RetrievalQA.from_chain_type(llm=llm,retriever=vectordb.as_retriever(search_kwargs={"k": 4}),return_source_documents=False)qa_chain = init_rag_chain()# ------------- Optional: live‑ingest a PDF the user uploads -------------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()# ------------- Configuration -------------st.set_page_config(page_title="📄 Multimodal Chat Assistant",146 unmodified linesmargin-bottom: 2rem;}</style>""", unsafe_allow_html=True)# Upload sectionuploaded_file = st.file_uploader("📤 Upload a PDF file", type=["pdf"])if uploaded_file is not None:with st.spinner("📚 Ingesting document..."):ingest_pdf(uploaded_file.read(), uploaded_file.name)st.success("✅ Document ingested. Ask away!")# Chat UIif "chat_history" not in st.session_state:st.session_state.chat_history = []prompt = st.text_input("💬 Ask a question about the document")if prompt:st.session_state.chat_history.append({"role": "user", "content": prompt})with st.spinner("🤔 Thinking..."):response = qa_chain.run(prompt)st.session_state.chat_history.append({"role": "assistant", "content": response})# Display chat historyfor msg in st.session_state.chat_history:if msg["role"] == "user":st.markdown(f"<div class='message-bubble'><b>🧑 You:</b> {msg['content']}</div>", unsafe_allow_html=True)else:st.markdown(f"<div class='message-bubble bot'><b>🤖 Bot:</b> {msg['content']}</div>", unsafe_allow_html=True)
app.py+70-284