EDITH02 commited on
Commit
652cce6
·
verified ·
1 Parent(s): b2ddd19

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +111 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,113 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
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] + "...")