shiva232 commited on
Commit
f555f9f
Β·
verified Β·
1 Parent(s): c80e06f

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +129 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,131 @@
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 streamlit as st
2
+ from PyPDF2 import PdfReader
3
 
4
+ # βœ… Updated LangChain imports
5
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
6
+ from langchain_community.embeddings import HuggingFaceEmbeddings
7
+ from langchain_community.vectorstores import FAISS
8
+
9
+ from transformers import pipeline
10
+
11
+ # -------------------------------
12
+ # PAGE CONFIG
13
+ # -------------------------------
14
+ st.set_page_config(
15
+ page_title="Multi-PDF Chat Agent",
16
+ page_icon="πŸ“„",
17
+ layout="wide"
18
+ )
19
+
20
+ st.title("πŸ“„ Multi-PDF Chat Agent")
21
+ st.caption("Upload PDFs and ask questions from them")
22
+
23
+ # -------------------------------
24
+ # SESSION STATE
25
+ # -------------------------------
26
+ if "vector_store" not in st.session_state:
27
+ st.session_state.vector_store = None
28
+
29
+ # -------------------------------
30
+ # LOAD QA MODEL (FIXED)
31
+ # -------------------------------
32
+ @st.cache_resource
33
+ def load_qa_pipeline():
34
+ return pipeline(
35
+ "question-answering",
36
+ model="distilbert-base-cased-distilled-squad"
37
+ )
38
+
39
+ qa_pipeline = load_qa_pipeline()
40
+
41
+ # -------------------------------
42
+ # SIDEBAR
43
+ # -------------------------------
44
+ with st.sidebar:
45
+ st.header("πŸ“‚ Upload PDFs")
46
+
47
+ uploaded_files = st.file_uploader(
48
+ "Upload one or more PDF files",
49
+ type="pdf",
50
+ accept_multiple_files=True
51
+ )
52
+
53
+ if st.button("⚑ Process PDFs"):
54
+ if not uploaded_files:
55
+ st.warning("Please upload at least one PDF.")
56
+ else:
57
+ with st.spinner("Processing documents..."):
58
+
59
+ text = ""
60
+
61
+ # βœ… Extract text safely
62
+ for file in uploaded_files:
63
+ pdf_reader = PdfReader(file)
64
+ for page in pdf_reader.pages:
65
+ page_text = page.extract_text()
66
+ if page_text:
67
+ text += page_text
68
+
69
+ if not text.strip():
70
+ st.error("No readable text found in PDFs.")
71
+ else:
72
+ # βœ… Split text
73
+ splitter = RecursiveCharacterTextSplitter(
74
+ chunk_size=800,
75
+ chunk_overlap=100
76
+ )
77
+ chunks = splitter.split_text(text)
78
+
79
+ # βœ… Embeddings
80
+ embeddings = HuggingFaceEmbeddings(
81
+ model_name="sentence-transformers/all-MiniLM-L6-v2"
82
+ )
83
+
84
+ # βœ… Vector store
85
+ vector_store = FAISS.from_texts(
86
+ texts=chunks,
87
+ embedding=embeddings
88
+ )
89
+
90
+ st.session_state.vector_store = vector_store
91
+ st.success("βœ… PDFs processed successfully!")
92
+
93
+ # -------------------------------
94
+ # MAIN CHAT
95
+ # -------------------------------
96
+ if st.session_state.vector_store:
97
+
98
+ st.subheader("πŸ’¬ Ask Questions")
99
+
100
+ question = st.text_input(
101
+ "Enter your question:",
102
+ placeholder="What is the main topic?"
103
+ )
104
+
105
+ if question:
106
+ with st.spinner("Thinking..."):
107
+
108
+ # βœ… Retrieve relevant chunks
109
+ docs = st.session_state.vector_store.similarity_search(
110
+ question,
111
+ k=2 # reduced for HF memory safety
112
+ )
113
+
114
+ context = "\n".join([doc.page_content for doc in docs])
115
+
116
+ # βœ… Get answer
117
+ result = qa_pipeline(
118
+ question=question,
119
+ context=context
120
+ )
121
+
122
+ st.markdown("### βœ… Answer")
123
+ st.write(result["answer"])
124
+
125
+ st.markdown("### πŸ“š Source Excerpts")
126
+ for i, doc in enumerate(docs):
127
+ st.markdown(f"**Excerpt {i+1}:**")
128
+ st.write(doc.page_content)
129
+
130
+ else:
131
+ st.info("πŸ‘ˆ Upload and process PDFs to begin.")