Update app.py
Browse files5 unmodified lines67891011121314151617181920212223242526272829303132333435361 unmodified line38394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181195 unmodified linesfrom langchain.chains import ConversationalRetrievalChainfrom langchain.memory import ConversationBufferMemoryimport os#from dotenv import load_dotenvimport requestsfrom bs4 import BeautifulSoupimport gradio as gr# Load environment variables#load_dotenv()GROQ_API_KEY = os.environ.get("GROQ_API_KEY")# Initialize global session statessession_state = {"messages": [],"qa_chain": None,"current_blog_url": None,"blog_content": None}# Function to fetch and extract blog textdef fetch_blog_text(url: str) -> str:response = requests.get(url)soup = BeautifulSoup(response.text, "html.parser")paragraphs = [p.get_text() for p in soup.find_all("p")]return "\n".join(paragraphs)# Function to create vector store from blog textdef create_vector_store(text: str):splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)chunks = splitter.split_text(text)1 unmodified linevectordb = Chroma.from_texts(chunks, embeddings)return vectordb# Set up the RAG chaindef setup_chain(vectordb):memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)llm = ChatGroq(api_key=GROQ_API_KEY, model="qwen-qwq-32b")qa_chain = ConversationalRetrievalChain.from_llm(llm, vectordb.as_retriever(), memory=memory)return qa_chain# Load and process blog functiondef load_blog(blog_url):try:text = fetch_blog_text(blog_url)vectordb = create_vector_store(text)session_state["qa_chain"] = setup_chain(vectordb)session_state["current_blog_url"] = blog_urlsession_state["blog_content"] = textsession_state["messages"] = []return f"β Blog loaded! You can now ask questions.\n\nPreview:\n{text[:1000]}{'...' if len(text) > 1000 else ''}"except Exception as e:return f"β Error loading blog: {str(e)}"# Chat handlerdef chat_with_blog(question):if not session_state["qa_chain"]:return "β Please load a blog first."session_state["messages"].append({"role": "user", "content": question})try:result = session_state["qa_chain"]({"question": question,"chat_history": [(m["content"] if m["role"] == "user" else "",m["content"] if m["role"] == "assistant" else "")for m in session_state["messages"][:-1]]})response = result["answer"]session_state["messages"].append({"role": "assistant", "content": response})return responseexcept Exception as e:return f"β Error: {str(e)}"# Gradio UIdef main():with gr.Blocks(theme=gr.themes.Base(), css="""textarea, input, button {font-size: 1.2em;}.chat-box {height: 300px;overflow-y: auto;background-color: #1f1f1f;color: white;padding: 1em;border-radius: 8px;}""") as demo:gr.Markdown("# π Blog Bot\nYour AI-powered blog analysis companion")with gr.Row():blog_url_input = gr.Textbox(label="Enter Blog URL", placeholder="Paste blog URL here...")load_btn = gr.Button("β¨ Load Blog")blog_preview = gr.Markdown("", label="Blog Preview")with gr.Row():chat_input = gr.Textbox(label="Ask a question about the blog...", lines=2)send_btn = gr.Button("Send")chat_output = gr.Textbox(label="Response", lines=4)load_btn.click(fn=load_blog, inputs=blog_url_input, outputs=blog_preview)send_btn.click(fn=chat_with_blog, inputs=chat_input, outputs=chat_output)demo.launch()if __name__ == "__main__":main()5 unmodified lines67891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541 unmodified line1561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442455 unmodified linesfrom langchain.chains import ConversationalRetrievalChainfrom langchain.memory import ConversationBufferMemoryimport osfrom dotenv import load_dotenvimport requestsfrom bs4 import BeautifulSoupimport streamlit as st# Load environment variablesload_dotenv()GROQ_API_KEY = os.getenv("GROQ_API_KEY")# Custom CSSst.markdown("""<style>/* Main container */.stApp {background-color: #0f0f0f;color: white;}/* Headers */h1 {color: #ff0000 !important;font-size: 2.5em !important;text-align: center;margin-bottom: 10px !important;}/* Subheaders */h2, h3 {color: #aaaaaa !important;font-size: 1.5em !important;}/* Text input */.stTextInput > div > div > input {background-color: #1f1f1f !important;color: white !important;border: 1px solid #303030 !important;border-radius: 4px !important;font-size: 1.2em !important;padding: 12px !important;height: 60px !important;}/* Buttons */.stButton > button {background-color: #ff0000 !important;color: white !important;border: none !important;border-radius: 4px !important;padding: 12px 24px !important;font-weight: 500 !important;font-size: 1.2em !important;width: 100% !important;margin: 10px 0 !important;}.stButton > button:hover {background-color: #cc0000 !important;}/* Chat messages */.stChatMessage {background-color: #1f1f1f !important;border: 1px solid #303030 !important;border-radius: 8px !important;padding: 16px !important;margin: 12px 0 !important;font-size: 1.1em !important;}.stChatMessage[data-testid="user-message"] {border-left: 4px solid #ff0000 !important;}.stChatMessage[data-testid="assistant-message"] {border-left: 4px solid #3ea6ff !important;}/* Blog content preview */.blog-preview {background-color: #1f1f1f !important;border: 1px solid #303030 !important;border-radius: 8px !important;padding: 20px !important;margin: 20px 0 !important;max-height: 400px !important;overflow-y: auto !important;font-size: 1.1em !important;line-height: 1.6 !important;}/* Chat input */.stChatInput > div > div > textarea {background-color: #1f1f1f !important;color: white !important;border: 1px solid #303030 !important;border-radius: 4px !important;font-size: 1.2em !important;padding: 12px !important;min-height: 80px !important;}/* Scrollbar styling */::-webkit-scrollbar {width: 10px;}::-webkit-scrollbar-track {background: #1f1f1f;}::-webkit-scrollbar-thumb {background: #303030;border-radius: 5px;}::-webkit-scrollbar-thumb:hover {background: #404040;}</style>""", unsafe_allow_html=True)# Initialize session stateif "messages" not in st.session_state:st.session_state.messages = []if "qa_chain" not in st.session_state:st.session_state.qa_chain = Noneif "current_blog_url" not in st.session_state:st.session_state.current_blog_url = Noneif "blog_content" not in st.session_state:st.session_state.blog_content = None# 1. Function to fetch and extract blog textdef fetch_blog_text(url: str) -> str:response = requests.get(url)soup = BeautifulSoup(response.text, "html.parser")paragraphs = [p.get_text() for p in soup.find_all("p")]return "\n".join(paragraphs)# 2. Function to create vector store from blog textdef create_vector_store(text: str):splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)chunks = splitter.split_text(text)1 unmodified linevectordb = Chroma.from_texts(chunks, embeddings)return vectordb# 3. Set up the RAG chaindef setup_chain(vectordb):memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)llm = ChatGroq(api_key=GROQ_API_KEY, model="gemma2-9b-it")qa_chain = ConversationalRetrievalChain.from_llm(llm, vectordb.as_retriever(), memory=memory)return qa_chain# App titlest.markdown("<h1>Blog Bot π</h1>", unsafe_allow_html=True)st.markdown("<p style='text-align: center; color: #aaaaaa; font-size: 1.2em;'>Your AI-powered blog analysis companion</p>", unsafe_allow_html=True)# Create two columnscol1, col2 = st.columns(2)with col1:# Blog URL inputblog_url = st.text_input("π Enter Blog URL", placeholder="Paste your blog URL here...", key="blog_url_input")# Process buttonif st.button("β¨ Load Blog", key="load_blog_btn"):if not blog_url:st.error("Please enter a blog URL.")else:try:with st.spinner("π Processing blog content..."):# Fetch and process blog contenttext = fetch_blog_text(blog_url)st.session_state.blog_content = text # Store blog contentvectordb = create_vector_store(text)st.session_state.qa_chain = setup_chain(vectordb)st.session_state.current_blog_url = blog_urlst.session_state.messages = [] # Clear chat historyst.success("β Blog content loaded! You can now ask questions about it.")except Exception as e:st.error(f"β Error processing blog: {str(e)}")# Display blog content previewif st.session_state.blog_content:st.markdown("### π Blog Content Preview")st.markdown(f"""<div class="blog-preview">{st.session_state.blog_content[:2000] + "..." if len(st.session_state.blog_content) > 2000 else st.session_state.blog_content}</div>""", unsafe_allow_html=True)with col2:# Chat interfacest.markdown("### π¬ Chat")# Display chat messagesfor message in st.session_state.messages:with st.chat_message(message["role"]):st.markdown(message["content"])# Chat inputif prompt := st.chat_input("Ask a question about the blog...", key="chat_input"):if not st.session_state.qa_chain:st.error("Please load a blog first.")else:# Add user message to chat historyst.session_state.messages.append({"role": "user", "content": prompt})# Display user messagewith st.chat_message("user"):st.markdown(prompt)try:# Get AI responsewith st.spinner("π€ Thinking..."):result = st.session_state.qa_chain({"question": prompt,"chat_history": [(m["content"] if m["role"] == "user" else "", m["content"] if m["role"] == "assistant" else "")for m in st.session_state.messages[:-1]]})response = result["answer"]# Add assistant message to chat historyst.session_state.messages.append({"role": "assistant", "content": response})# Display assistant messagewith st.chat_message("assistant"):st.markdown(response)except Exception as e:st.error(f"β Error: {str(e)}")
app.py+212-86