Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 3 |
+
from langchain_groq import ChatGroq
|
| 4 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 5 |
+
from langchain_community.vectorstores import Chroma
|
| 6 |
+
from langchain.chains import ConversationalRetrievalChain
|
| 7 |
+
from langchain.memory import ConversationBufferMemory
|
| 8 |
+
import os
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
import requests
|
| 11 |
+
from bs4 import BeautifulSoup
|
| 12 |
+
import gradio as gr
|
| 13 |
+
|
| 14 |
+
# Load environment variables
|
| 15 |
+
load_dotenv()
|
| 16 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 17 |
+
|
| 18 |
+
# Initialize global session states
|
| 19 |
+
session_state = {
|
| 20 |
+
"messages": [],
|
| 21 |
+
"qa_chain": None,
|
| 22 |
+
"current_blog_url": None,
|
| 23 |
+
"blog_content": None
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
# Function to fetch and extract blog text
|
| 27 |
+
def fetch_blog_text(url: str) -> str:
|
| 28 |
+
response = requests.get(url)
|
| 29 |
+
soup = BeautifulSoup(response.text, "html.parser")
|
| 30 |
+
paragraphs = [p.get_text() for p in soup.find_all("p")]
|
| 31 |
+
return "\n".join(paragraphs)
|
| 32 |
+
|
| 33 |
+
# Function to create vector store from blog text
|
| 34 |
+
def create_vector_store(text: str):
|
| 35 |
+
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
|
| 36 |
+
chunks = splitter.split_text(text)
|
| 37 |
+
embeddings = HuggingFaceEmbeddings()
|
| 38 |
+
vectordb = Chroma.from_texts(chunks, embeddings)
|
| 39 |
+
return vectordb
|
| 40 |
+
|
| 41 |
+
# Set up the RAG chain
|
| 42 |
+
def setup_chain(vectordb):
|
| 43 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
| 44 |
+
llm = ChatGroq(api_key=GROQ_API_KEY, model="gemma2-9b-it")
|
| 45 |
+
qa_chain = ConversationalRetrievalChain.from_llm(
|
| 46 |
+
llm, vectordb.as_retriever(), memory=memory
|
| 47 |
+
)
|
| 48 |
+
return qa_chain
|
| 49 |
+
|
| 50 |
+
# Load and process blog function
|
| 51 |
+
def load_blog(blog_url):
|
| 52 |
+
try:
|
| 53 |
+
text = fetch_blog_text(blog_url)
|
| 54 |
+
vectordb = create_vector_store(text)
|
| 55 |
+
session_state["qa_chain"] = setup_chain(vectordb)
|
| 56 |
+
session_state["current_blog_url"] = blog_url
|
| 57 |
+
session_state["blog_content"] = text
|
| 58 |
+
session_state["messages"] = []
|
| 59 |
+
return f"β
Blog loaded! You can now ask questions.\n\nPreview:\n{text[:1000]}{'...' if len(text) > 1000 else ''}"
|
| 60 |
+
except Exception as e:
|
| 61 |
+
return f"β Error loading blog: {str(e)}"
|
| 62 |
+
|
| 63 |
+
# Chat handler
|
| 64 |
+
def chat_with_blog(question):
|
| 65 |
+
if not session_state["qa_chain"]:
|
| 66 |
+
return "β Please load a blog first."
|
| 67 |
+
|
| 68 |
+
session_state["messages"].append({"role": "user", "content": question})
|
| 69 |
+
try:
|
| 70 |
+
result = session_state["qa_chain"]({
|
| 71 |
+
"question": question,
|
| 72 |
+
"chat_history": [
|
| 73 |
+
(m["content"] if m["role"] == "user" else "",
|
| 74 |
+
m["content"] if m["role"] == "assistant" else "")
|
| 75 |
+
for m in session_state["messages"][:-1]
|
| 76 |
+
]
|
| 77 |
+
})
|
| 78 |
+
response = result["answer"]
|
| 79 |
+
session_state["messages"].append({"role": "assistant", "content": response})
|
| 80 |
+
return response
|
| 81 |
+
except Exception as e:
|
| 82 |
+
return f"β Error: {str(e)}"
|
| 83 |
+
|
| 84 |
+
# Gradio UI
|
| 85 |
+
def main():
|
| 86 |
+
with gr.Blocks(theme=gr.themes.Base(), css="""
|
| 87 |
+
textarea, input, button {
|
| 88 |
+
font-size: 1.2em;
|
| 89 |
+
}
|
| 90 |
+
.chat-box {
|
| 91 |
+
height: 300px;
|
| 92 |
+
overflow-y: auto;
|
| 93 |
+
background-color: #1f1f1f;
|
| 94 |
+
color: white;
|
| 95 |
+
padding: 1em;
|
| 96 |
+
border-radius: 8px;
|
| 97 |
+
}
|
| 98 |
+
""") as demo:
|
| 99 |
+
gr.Markdown("# π Blog Bot\nYour AI-powered blog analysis companion")
|
| 100 |
+
|
| 101 |
+
with gr.Row():
|
| 102 |
+
blog_url_input = gr.Textbox(label="Enter Blog URL", placeholder="Paste blog URL here...")
|
| 103 |
+
load_btn = gr.Button("β¨ Load Blog")
|
| 104 |
+
|
| 105 |
+
blog_preview = gr.Markdown("", label="Blog Preview")
|
| 106 |
+
|
| 107 |
+
with gr.Row():
|
| 108 |
+
chat_input = gr.Textbox(label="Ask a question about the blog...", lines=2)
|
| 109 |
+
send_btn = gr.Button("Send")
|
| 110 |
+
|
| 111 |
+
chat_output = gr.Textbox(label="Response", lines=4)
|
| 112 |
+
|
| 113 |
+
load_btn.click(fn=load_blog, inputs=blog_url_input, outputs=blog_preview)
|
| 114 |
+
send_btn.click(fn=chat_with_blog, inputs=chat_input, outputs=chat_output)
|
| 115 |
+
|
| 116 |
+
demo.launch()
|
| 117 |
+
|
| 118 |
+
if __name__ == "__main__":
|
| 119 |
+
main()
|