Spaces:
Sleeping
Sleeping
Update app.py
Browse files12344567891110111213141516181718201920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071146 unmodified lines218219220173174175176177178179180181182183184185186187188189190191192193194195196197198199221222201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322223224325326327328329330331332333334225226336337338339340341342343344345227228229230347348231232233234350351352353354355356357358359360361362363364365366367368369370371372373374375376377235236237380381382383384385386387238239388240390391392241242393394395396397398399400243244403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463245246247248249# ---- Standard libs ----import os, tempfilefrom datetime import datetimeimport json
# ---- Streamlit ----import streamlit as st
# ---- Load environment variables (.env) ----from dotenv import load_dotenvload_dotenv()load_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 PyPDFLoaderfrom langchain_community.document_loaders import UnstructuredFileLoaderfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_chroma import Chroma
# ------------- Oneβtime chain initialiser -------------@st.cache_resource(show_spinner=False)def init_rag_chain(): # 1οΈβ£ Embeddings embedding = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
# 2οΈβ£ Persisted vector DB vectordb = Chroma( persist_directory="./rag_db", embedding_function=embedding )
llm = ChatGroq( groq_api_key=os.getenv("GROQ_API_KEY"), # <--- THIS is critical model="llama3-70b-8192", temperature=0.2, )
# 4οΈβ£ Retrievalβaugmented QA chain return 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.name
docs = 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 lines margin-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")""", unsafe_allow_html=True)
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.name
loader = 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 chunks non_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 0
vectordb.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 selection model_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 statistics st.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 list if 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 button if 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)
uploaded_file = st.file_uploader("π€ Upload a PDF file", type=["pdf"])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() with st.spinner("π Ingesting document..."): ingest_pdf(uploaded_file.read(), uploaded_file.name) st.success("β
Document ingested. Ask away!")
# Chat interfacest.markdown('<div class="chat-container">', unsafe_allow_html=True)# Chat UIif "chat_history" not in st.session_state: st.session_state.chat_history = []
# 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 += 1 st.rerun()
# Chat inputprompt = st.text_input( "π¬ Ask a question about your document", placeholder="Type your question here...", key="chat_input")prompt = st.text_input("π¬ Ask a question about the document")
if prompt: # Add user message st.session_state.chat_history.append({ "role": "user", "content": prompt, "timestamp": datetime.now().strftime("%H:%M") }) st.session_state.total_questions += 1 st.session_state.chat_history.append({"role": "user", "content": prompt})
# Generate response with st.spinner("π€ Thinking..."): try: response = qa_chain.run(prompt) st.session_state.chat_history.append({ response = qa_chain.run(prompt) st.session_state.chat_history.append({"role": "assistant", "content": response}) "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 responses col1, 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)for 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