Spaces:
Sleeping
Sleeping
Update app.py
Browse files6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344452 unmodified lines484950515253545556575859606162636465666768697071727374751 unmodified line77787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653666 unmodified lines# ---- 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}),2 unmodified linesqa_chain = init_rag_chain()#------------- PDF ingestion handler -------------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)chunks = splitter.split_documents(docs)vectordb.add_documents(chunks)vectordb.persist()# ------------- Streamlit page config -------------st.set_page_config(page_title="π Multimodal Chat Assistant",page_icon="π€",1 unmodified lineinitial_sidebar_state="expanded")# ------------- Chat UI + LLM response -------------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 history -------------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)# ------------- Premium CSS Styling -------------st.markdown("""<style>@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');.main {background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);min-height: 100vh;font-family: 'Inter', sans-serif;}.stApp {background: transparent;}.chat-container {background: rgba(255, 255, 255, 0.95);backdrop-filter: blur(20px);border-radius: 20px;padding: 2rem;margin: 1rem 0;box-shadow: 0 20px 40px rgba(0,0,0,0.1);border: 1px solid rgba(255,255,255,0.2);}.message-user {background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);color: white;padding: 1rem 1.5rem;border-radius: 20px 20px 5px 20px;margin: 0.5rem 0 0.5rem auto;max-width: 80%;box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);animation: slideInRight 0.3s ease-out;}.message-bot {background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);color: white;padding: 1rem 1.5rem;border-radius: 20px 20px 20px 5px;margin: 0.5rem auto 0.5rem 0;max-width: 80%;box-shadow: 0 4px 15px rgba(245, 87, 108, 0.3);animation: slideInLeft 0.3s ease-out;}@keyframes slideInRight {from { transform: translateX(100px); opacity: 0; }to { transform: translateX(0); opacity: 1; }}@keyframes slideInLeft {from { transform: translateX(-100px); opacity: 0; }to { transform: translateX(0); opacity: 1; }}.upload-area {background: rgba(255, 255, 255, 0.1);border: 2px dashed rgba(255, 255, 255, 0.3);border-radius: 15px;padding: 2rem;text-align: center;transition: all 0.3s ease;}.upload-area:hover {background: rgba(255, 255, 255, 0.2);border-color: rgba(255, 255, 255, 0.5);}.stats-card {background: rgba(255, 255, 255, 0.1);backdrop-filter: blur(10px);border-radius: 15px;padding: 1.5rem;margin: 0.5rem 0;border: 1px solid rgba(255, 255, 255, 0.2);}.feature-card {background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0.05) 100%);backdrop-filter: blur(10px);border-radius: 15px;padding: 1.5rem;margin: 1rem 0;border: 1px solid rgba(255, 255, 255, 0.2);transition: transform 0.3s ease;}.feature-card:hover {transform: translateY(-5px);}.stTextInput > div > div > input {background: rgba(255, 255, 255, 0.9);border: 2px solid rgba(255, 255, 255, 0.3);border-radius: 25px;padding: 15px 20px;font-size: 16px;transition: all 0.3s ease;}.stTextInput > div > div > input:focus {border-color: #667eea;box-shadow: 0 0 20px rgba(102, 126, 234, 0.3);}.sidebar .stSelectbox > div > div {background: rgba(255, 255, 255, 0.1);border-radius: 10px;}.typing-indicator {display: inline-block;width: 20px;height: 20px;border-radius: 50%;background: #667eea;animation: typing 1.4s infinite ease-in-out;}@keyframes typing {0%, 80%, 100% { transform: scale(0); }40% { transform: scale(1); }}.premium-title {background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);-webkit-background-clip: text;-webkit-text-fill-color: transparent;font-size: 3rem;font-weight: 700;text-align: center;margin-bottom: 1rem;}.subtitle {color: rgba(255, 255, 255, 0.8);text-align: center;font-size: 1.2rem;margin-bottom: 2rem;}</style>""", unsafe_allow_html=True)# ------------- 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)t.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>π 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)6 unmodified lines789101112131415161718192021222324252627282930313233342 unmodified lines3738394041424344454647484950515253545556571 unmodified line59606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751766 unmodified lines# ---- Load environment variables (.env) ----from dotenv import load_dotenvload_dotenv()# ---- RAG + Groq stack ----from langchain_groq import ChatGroqfrom langchain_huggingface import HuggingFaceEmbeddingsfrom langchain_chroma import Chromafrom langchain.chains import RetrievalQAfrom langchain_community.document_loaders import UnstructuredFileLoaderfrom langchain.text_splitter import RecursiveCharacterTextSplitter# ------------- Chain Initializer -------------@st.cache_resource(show_spinner=False)def init_rag_chain():embedding = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")vectordb = Chroma(persist_directory="./rag_db", embedding_function=embedding)llm = ChatGroq(groq_api_key=os.getenv("GROQ_API_KEY"),model="llama3-70b-8192",temperature=0.2,)return RetrievalQA.from_chain_type(llm=llm,retriever=vectordb.as_retriever(search_kwargs={"k": 4}),2 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",page_icon="π€",1 unmodified lineinitial_sidebar_state="expanded")# ------------- Custom CSS for Styling -------------st.markdown("""<style>/* Remove padding */.block-container {padding-top: 2rem;padding-bottom: 2rem;}/* Title styling */.title {font-size: 3rem;font-weight: bold;color: #4A90E2;text-align: center;margin-bottom: 1.5rem;}/* Chat bubble styling */.chat-history {height: 500px;overflow-y: auto;background-color: #F9F9F9;border-radius: 12px;padding: 1rem;border: 1px solid #DDD;}.message-user {background-color: #DDF3FF;padding: 0.8rem;border-radius: 12px;margin-bottom: 0.5rem;text-align: left;}.message-bot {background-color: #E3FFE1;padding: 0.8rem;border-radius: 12px;margin-bottom: 0.5rem;text-align: left;}/* Text input spacing */.stTextInput > div > input {font-size: 1rem;padding: 0.7rem;border-radius: 8px;}/* Button style */.stButton>button {border-radius: 8px;background-color: #4A90E2;color: white;font-size: 1rem;padding: 0.5rem 1.2rem;}.stButton>button:hover {background-color: #357ABD;}</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 Chat Assistant")st.write("β’ Upload a PDF π")st.write("β’ Ask context-specific questions π¬")st.write("β’ Powered by **LLaMA 3 + Groq** β‘")if st.button("ποΈ Clear Chat History"):st.session_state.chat_history = []st.experimental_rerun()# ------------- App Title -------------st.markdown("<div class='title'>π PDF Chat Assistant</div>", unsafe_allow_html=True)# ------------- Upload UI -------------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!")# ------------- Chat UI State -------------if "chat_history" not in st.session_state:st.session_state.chat_history = []# ------------- Prompt Input with Button -------------col1, col2 = st.columns([5, 1])with col1:prompt = st.text_input("π¬ Type your question and press Enter", placeholder="Ask something about your PDF...")with col2:send_clicked = st.button("β‘οΈ Send")if prompt or send_clicked: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 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>π€ Bot:</b> {msg['content']}</div>", unsafe_allow_html=True)st.markdown("</div>", unsafe_allow_html=True)
app.py+122-312