-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
171 lines (120 loc) · 4.4 KB
/
Copy pathapp.py
File metadata and controls
171 lines (120 loc) · 4.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import os
import streamlit as st
from dotenv import load_dotenv
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import PyPDFLoader
from langchain_core.runnables import RunnablePassthrough
from langchain_core.prompts import ChatPromptTemplate
import tempfile
load_dotenv()
st.set_page_config(
page_title="Chatbot with Memory + PDF Q&A",
page_icon="🤖",
layout="wide"
)
st.title("**Chatbot with Memory**")
st.write("Upload a PDF and ask questions. The chatbot remembers the conversation.")
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
if "vectorstore" not in st.session_state:
st.session_state.vectorstore = None
if "qa_chain" not in st.session_state:
st.session_state.qa_chain = None
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
if not GOOGLE_API_KEY:
st.error("Missing GOOGLE_API_KEY. Add it inside your .env file.")
st.stop()
llm = ChatGoogleGenerativeAI(
model="gemini-2.5-flash",
google_api_key=GOOGLE_API_KEY,
temperature=0.3
)
embeddings = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)
def process_pdf(uploaded_file):
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
temp_file.write(uploaded_file.read())
temp_path = temp_file.name
loader = PyPDFLoader(temp_path)
documents = loader.load()
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200
)
chunks = text_splitter.split_documents(documents)
vectorstore = FAISS.from_documents(
documents=chunks,
embedding=embeddings
)
os.remove(temp_path)
return vectorstore
def create_qa_chain(vectorstore):
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})
prompt = ChatPromptTemplate.from_template(
"""Answer the question based on the following context:
Context: {context}
Question: {question}
Answer:"""
)
def format_docs(docs):
return "\n".join([doc.page_content for doc in docs])
chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| prompt
| llm
)
return {"chain": chain, "retriever": retriever}
with st.sidebar:
st.header("Upload PDF")
uploaded_file = st.file_uploader(
"Choose a PDF file",
type=["pdf"]
)
if uploaded_file is not None:
if st.button("Process PDF"):
with st.spinner("Processing PDF..."):
vectorstore = process_pdf(uploaded_file)
st.session_state.vectorstore = vectorstore
st.session_state.qa_chain = create_qa_chain(vectorstore)
st.success("PDF processed successfully!")
if st.button("Clear Chat"):
st.session_state.chat_history = []
st.session_state.qa_chain = None
st.session_state.vectorstore = None
st.success("Chat cleared.")
for message in st.session_state.chat_history:
with st.chat_message(message["role"]):
st.write(message["content"])
user_question = st.chat_input("Ask something...")
if user_question:
st.session_state.chat_history.append({
"role": "user",
"content": user_question
})
with st.chat_message("user"):
st.write(user_question)
with st.chat_message("assistant"):
with st.spinner("Thinking..."):
if st.session_state.qa_chain:
chain = st.session_state.qa_chain["chain"]
retriever = st.session_state.qa_chain["retriever"]
result = chain.invoke(user_question)
answer = result.content
st.write(answer)
with st.expander("Sources"):
docs = retriever.invoke(user_question)
for i, doc in enumerate(docs):
st.write(f"Source {i + 1}")
st.write(doc.page_content[:500])
else:
normal_response = llm.invoke(user_question)
answer = normal_response.content
st.write(answer)
st.session_state.chat_history.append({
"role": "assistant",
"content": answer
})