Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +111 -38
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,113 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
st.
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
import asyncio
|
| 4 |
import streamlit as st
|
| 5 |
+
from langchain_community.document_loaders import PyPDFLoader
|
| 6 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 7 |
+
from langchain_community.vectorstores import FAISS
|
| 8 |
+
from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
|
| 9 |
+
from langchain.chains import RetrievalQA
|
| 10 |
|
| 11 |
+
# ---------------- Handle Event Loop ----------------
|
| 12 |
+
# Sometimes async libraries complain if there's no running event loop.
|
| 13 |
+
# This makes sure one exists before we run the app.
|
| 14 |
+
try:
|
| 15 |
+
asyncio.get_event_loop()
|
| 16 |
+
except RuntimeError:
|
| 17 |
+
asyncio.set_event_loop(asyncio.new_event_loop())
|
| 18 |
+
|
| 19 |
+
# ---------------- Streamlit Page Setup ----------------
|
| 20 |
+
st.set_page_config(page_title="PDF RAG Chatbot", layout="wide")
|
| 21 |
+
st.title("PDF RAG Chatbot with Gemini + LangChain")
|
| 22 |
+
|
| 23 |
+
# ---------------- API Key Setup ----------------
|
| 24 |
+
# The app will not run if we don't have a Gemini API Key in environment variables.
|
| 25 |
+
apiKey = os.getenv("GEMINI_API_KEY")
|
| 26 |
+
if not apiKey:
|
| 27 |
+
st.error("Please set GEMINI_API_KEY as an environment variable or in Streamlit secrets.")
|
| 28 |
+
st.stop()
|
| 29 |
+
|
| 30 |
+
# ---------------- Sidebar for File Upload ----------------
|
| 31 |
+
st.sidebar.header("Upload PDFs")
|
| 32 |
+
uploaded_files = st.sidebar.file_uploader(
|
| 33 |
+
"Select PDF files to upload", type=["pdf"], accept_multiple_files=True
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# Show uploaded file names in sidebar
|
| 37 |
+
if uploaded_files:
|
| 38 |
+
st.sidebar.subheader("Uploaded Files:")
|
| 39 |
+
for f in uploaded_files:
|
| 40 |
+
st.sidebar.write(f"- {f.name}")
|
| 41 |
+
|
| 42 |
+
# ---------------- Build Index ----------------
|
| 43 |
+
# When user clicks the button, process PDFs into chunks and build vector index
|
| 44 |
+
if st.sidebar.button("Build Index"):
|
| 45 |
+
if not uploaded_files:
|
| 46 |
+
st.sidebar.warning("Please upload at least one PDF before building index.")
|
| 47 |
+
st.stop()
|
| 48 |
+
|
| 49 |
+
docs = []
|
| 50 |
+
for uploaded_file in uploaded_files:
|
| 51 |
+
# Save the uploaded file temporarily so PyPDFLoader can read it
|
| 52 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
|
| 53 |
+
tmp_file.write(uploaded_file.read())
|
| 54 |
+
tmp_path = tmp_file.name
|
| 55 |
+
|
| 56 |
+
# Load PDF and extract text
|
| 57 |
+
loader = PyPDFLoader(tmp_path)
|
| 58 |
+
docs.extend(loader.load())
|
| 59 |
+
|
| 60 |
+
# Break documents into smaller chunks for better retrieval
|
| 61 |
+
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
|
| 62 |
+
chunks = splitter.split_documents(docs)
|
| 63 |
+
|
| 64 |
+
# Convert chunks into embeddings and store them in FAISS (vector database)
|
| 65 |
+
embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=apiKey)
|
| 66 |
+
vectordb = FAISS.from_documents(chunks, embeddings)
|
| 67 |
+
|
| 68 |
+
# Store retriever in session so it can be reused in chat
|
| 69 |
+
st.session_state.retriever = vectordb.as_retriever(search_kwargs={"k": 5})
|
| 70 |
+
st.sidebar.success(f"Index created with {len(chunks)} chunks from {len(uploaded_files)} file(s).")
|
| 71 |
+
|
| 72 |
+
# ---------------- Chat Section ----------------
|
| 73 |
+
# This section creates a chatbot-like interface using chat history
|
| 74 |
+
if "retriever" in st.session_state:
|
| 75 |
+
llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", google_api_key=apiKey, temperature=0.2)
|
| 76 |
+
qa_chain = RetrievalQA.from_chain_type(
|
| 77 |
+
llm=llm,
|
| 78 |
+
retriever=st.session_state.retriever,
|
| 79 |
+
chain_type="stuff",
|
| 80 |
+
return_source_documents=True,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# Store chat messages so they persist between user inputs
|
| 84 |
+
if "messages" not in st.session_state:
|
| 85 |
+
st.session_state.messages = []
|
| 86 |
+
|
| 87 |
+
# Show old messages from history
|
| 88 |
+
for msg in st.session_state.messages:
|
| 89 |
+
with st.chat_message(msg["role"]):
|
| 90 |
+
st.markdown(msg["content"])
|
| 91 |
+
|
| 92 |
+
# Input box for user to ask questions
|
| 93 |
+
if query := st.chat_input("Ask something about your PDFs..."):
|
| 94 |
+
# Save user query into chat history
|
| 95 |
+
st.session_state.messages.append({"role": "user", "content": query})
|
| 96 |
+
with st.chat_message("user"):
|
| 97 |
+
st.markdown(query)
|
| 98 |
+
|
| 99 |
+
# Run the question against the retrieval+LLM chain
|
| 100 |
+
with st.chat_message("assistant"):
|
| 101 |
+
with st.spinner("Thinking..."):
|
| 102 |
+
result = qa_chain.invoke(query)
|
| 103 |
+
response = result["result"]
|
| 104 |
+
st.markdown(response)
|
| 105 |
+
|
| 106 |
+
# Save assistant reply into chat history
|
| 107 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 108 |
+
|
| 109 |
+
# Optionally show which document chunks were used to answer
|
| 110 |
+
with st.expander("Sources"):
|
| 111 |
+
for i, doc in enumerate(result["source_documents"], 1):
|
| 112 |
+
st.markdown(f"Source {i} (Page {doc.metadata.get('page', 'N/A')})")
|
| 113 |
+
st.write(doc.page_content[:500] + "...")
|