ShubhangiAg commited on
Commit
30e793f
·
verified ·
1 Parent(s): 382d851

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +270 -62
app.py CHANGED
@@ -1,73 +1,281 @@
1
- # 📚 RAG Book Summarizer (Hugging Face Spaces ready)
2
- # This is a Streamlit app to summarize large books using RAG
3
- # Dependencies: streamlit, sentence-transformers, faiss-cpu, transformers, PyPDF2, openai
4
-
5
- import streamlit as st
6
- from PyPDF2 import PdfReader
7
- from sentence_transformers import SentenceTransformer
8
- import faiss
9
- import openai
10
  import os
 
 
11
  import numpy as np
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- # Load models
14
- st.set_page_config(page_title="Book Summarizer RAG", layout="wide")
15
- embedder = SentenceTransformer("all-MiniLM-L6-v2")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- openai.api_key = os.environ.get("OPENAI_API_KEY")
 
 
 
18
 
19
- st.title("📘 Book Summarizer using RAG")
20
- st.markdown("Upload a book in PDF format and get an AI-generated summary using Retrieval-Augmented Generation.")
21
 
22
- # 1. Upload PDF
23
- pdf_file = st.file_uploader("Upload a PDF book", type=["pdf"])
 
 
24
 
25
- if pdf_file:
26
- reader = PdfReader(pdf_file)
27
- text = "\n".join(page.extract_text() for page in reader.pages if page.extract_text())
28
 
29
- # 2. Chunk text
30
- def split_text(text, chunk_size=500, overlap=50):
31
- words = text.split()
 
 
 
 
 
32
  chunks = []
33
- for i in range(0, len(words), chunk_size - overlap):
34
- chunk = " ".join(words[i:i+chunk_size])
35
- chunks.append(chunk)
36
- return chunks
37
-
38
- chunks = split_text(text)
39
- st.success(f"Document split into {len(chunks)} chunks")
40
-
41
- # 3. Embed chunks
42
- with st.spinner("Embedding chunks and creating vector index..."):
43
- embeddings = embedder.encode(chunks, convert_to_numpy=True)
44
- index = faiss.IndexFlatL2(embeddings.shape[1])
45
- index.add(np.array(embeddings))
46
-
47
- # 4. Query-based summary
48
- query = st.text_input("Ask a question or request a summary (e.g., 'Summarize the book')", value="Summarize the book")
49
- if st.button("Generate Summary") and query:
50
- query_vec = embedder.encode([query])
51
- D, I = index.search(query_vec, k=5)
52
- retrieved_chunks = [chunks[i] for i in I[0]]
53
-
54
- context = "\n".join(retrieved_chunks)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  prompt = f"""
56
- You are an expert book summarizer.
57
- Using the context below, answer the query: "{query}"
58
-
59
- Context:
60
- {context}
61
-
62
- Answer:
63
- """
64
- with st.spinner("Generating summary with OpenAI..."):
65
- response = openai.ChatCompletion.create(
66
- model="gpt-3.5-turbo",
67
- messages=[{"role": "user", "content": prompt}],
68
- temperature=0.7,
69
- max_tokens=300
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  )
71
- answer = response.choices[0].message.content
72
- st.subheader("📄 Summary")
73
- st.write(answer)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import tempfile
3
+ import gradio as gr
4
  import numpy as np
5
+ from sklearn.metrics.pairwise import cosine_similarity
6
+ from sentence_transformers import SentenceTransformer
7
+
8
+ import google.generativeai as genai
9
+ import fitz # PyMuPDF
10
+ import traceback # Import traceback for detailed error logging
11
+
12
+ # Initialize embedding model
13
+ sbert_model = SentenceTransformer('all-MiniLM-L6-v2')
14
+
15
+ # Data storage
16
+ chunks = []
17
+ embeddings = np.array([])
18
+ # Global state for API key
19
+ # stored_api_key = None # Replaced by gr.State
20
+
21
+ def extract_text_from_pdf(pdf_file_path, start_page=None, end_page=None):
22
+ """
23
+ Extract text from PDF file, optionally from a specific page range.
24
+ Page numbers are 1-indexed.
25
+ """
26
+ doc = fitz.open(pdf_file_path)
27
+ text = ""
28
+
29
+ pages_to_process = []
30
+ num_pages_in_doc = doc.page_count
31
+
32
+ if start_page is not None and end_page is not None:
33
+ start_idx = start_page - 1
34
+ end_idx = end_page - 1
35
+
36
+ if 0 <= start_idx <= end_idx < num_pages_in_doc:
37
+ for i in range(start_idx, end_idx + 1):
38
+ pages_to_process.append(doc.load_page(i))
39
+ else:
40
+ print(f"Warning: Invalid page range received in extract_text_from_pdf. Defaulting to all pages.")
41
+ pages_to_process = [doc.load_page(i) for i in range(num_pages_in_doc)]
42
+ else:
43
+ pages_to_process = [doc.load_page(i) for i in range(num_pages_in_doc)]
44
+
45
+ for page_obj in pages_to_process:
46
+ text += page_obj.get_text()
47
+
48
+ doc.close()
49
+ return text, num_pages_in_doc
50
+
51
+
52
+ def chunk_text(text, chunk_size=1000, overlap=200):
53
+ """Split text into overlapping chunks"""
54
+ doc_chunks = []
55
+ for i in range(0, len(text), chunk_size - overlap):
56
+ chunk = text[i:i + chunk_size]
57
+ if len(chunk) > 100: # Ensure chunks are substantial
58
+ doc_chunks.append(chunk)
59
+ return doc_chunks
60
+
61
+ def process_pdf(pdf_file_obj, processing_mode, start_page_ui, end_page_ui):
62
+ """Process PDF (full or page range) and create embeddings."""
63
+ global chunks, embeddings
64
 
65
+ if pdf_file_obj is None:
66
+ chunks = []
67
+ embeddings = np.array([])
68
+ return "No PDF file provided. Please upload a PDF."
69
+
70
+ tmp_path = None
71
+ try:
72
+ with open(pdf_file_obj.name, "rb") as f_in:
73
+ pdf_bytes = f_in.read()
74
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp:
75
+ tmp.write(pdf_bytes)
76
+ tmp_path = tmp.name
77
+ except Exception as e:
78
+ if tmp_path and os.path.exists(tmp_path):
79
+ os.unlink(tmp_path)
80
+ return f"Error handling uploaded PDF file: {str(e)}"
81
+
82
+ actual_start_page, actual_end_page = None, None
83
+ page_info_str = "full document"
84
+ pdf_name = os.path.basename(pdf_file_obj.name)
85
+
86
+ try:
87
+ doc_for_page_count = fitz.open(tmp_path)
88
+ total_pages_in_doc = doc_for_page_count.page_count
89
+ doc_for_page_count.close()
90
+
91
+ if processing_mode == "Page Range":
92
+ if start_page_ui is None or end_page_ui is None:
93
+ raise ValueError("For 'Page Range' mode, both Start Page and End Page must be specified.")
94
+
95
+ s_page = int(start_page_ui)
96
+ e_page = int(end_page_ui)
97
+
98
+ if not (1 <= s_page <= total_pages_in_doc and \
99
+ 1 <= e_page <= total_pages_in_doc and \
100
+ s_page <= e_page):
101
+ raise ValueError(f"Invalid page range ({s_page}-{e_page}). Document has {total_pages_in_doc} pages.")
102
+ actual_start_page, actual_end_page = s_page, e_page
103
+ page_info_str = f"pages {s_page}-{e_page}"
104
+
105
+ text, _ = extract_text_from_pdf(tmp_path, start_page=actual_start_page, end_page=actual_end_page)
106
 
107
+ if not text.strip():
108
+ chunks = []
109
+ embeddings = np.array([])
110
+ return f"Processed {page_info_str} of '{pdf_name}', but no text content found. Old data cleared."
111
 
112
+ current_book_chunks = chunk_text(text)
 
113
 
114
+ if not current_book_chunks:
115
+ chunks = []
116
+ embeddings = np.array([])
117
+ return f"Processed {page_info_str} of '{pdf_name}', but no substantial chunks created. Old data cleared."
118
 
119
+ current_book_embeddings = sbert_model.encode(current_book_chunks)
 
 
120
 
121
+ chunks = current_book_chunks
122
+ embeddings = np.array(current_book_embeddings)
123
+
124
+ return f"Successfully processed {page_info_str} of '{pdf_name}'. Created {len(chunks)} chunks. Ready for questions."
125
+
126
+ except ValueError as ve:
127
+ return f"Error: {str(ve)}"
128
+ except Exception as e:
129
  chunks = []
130
+ embeddings = np.array([])
131
+ error_msg = f"Error processing '{pdf_name}' ({page_info_str}): {str(e)}\n{traceback.format_exc()}"
132
+ print(error_msg)
133
+ return error_msg
134
+ finally:
135
+ if tmp_path and os.path.exists(tmp_path):
136
+ os.unlink(tmp_path)
137
+
138
+
139
+ def retrieve_relevant_chunks(query, top_k=5):
140
+ """Retrieve most relevant chunks based on query."""
141
+ global chunks, embeddings
142
+
143
+ if not chunks or not isinstance(embeddings, np.ndarray) or embeddings.size == 0:
144
+ return ["No document processed or no content yielded. Please process a PDF."]
145
+
146
+ query_embedding = sbert_model.encode([query])[0]
147
+ similarities = cosine_similarity([query_embedding], embeddings)[0]
148
+
149
+ num_available_chunks = len(chunks)
150
+ actual_top_k = min(top_k, num_available_chunks)
151
+
152
+ if actual_top_k == 0:
153
+ return ["No relevant chunks found."]
154
+
155
+ top_indices = np.argsort(similarities)[-actual_top_k:][::-1]
156
+ # Return the actual chunk text
157
+ top_chunks_text = [chunks[i] for i in top_indices]
158
+
159
+ return top_chunks_text
160
+
161
+ def generate_response(query, current_api_key_state):
162
+ """Generate response using Gemini API and RAG, including sources."""
163
+ if not current_api_key_state:
164
+ return "API key not set. Please enter your API key and click 'Confirm API Key'.", "" # Return empty string for sources
165
+
166
+ try:
167
+ genai.configure(api_key=current_api_key_state)
168
+ context_chunks = retrieve_relevant_chunks(query)
169
+
170
+ if not context_chunks or "No document" in context_chunks[0] or "No relevant chunks" in context_chunks[0]:
171
+ return f"Could not retrieve relevant context. Ensure a PDF is processed.\n\nDetails: {context_chunks[0]}", "" # Return empty string for sources
172
+
173
+ context_for_prompt = "\n\n".join(context_chunks)
174
+
175
  prompt = f"""
176
+ Based on the following context from a book, please answer the query.
177
+ CONTEXT:
178
+ {context_for_prompt}
179
+ QUERY:
180
+ {query}
181
+ Please provide a helpful and accurate response based only on the information in the context. If the context doesn't provide an answer, say so.
182
+ """
183
+
184
+ gemini_model_instance = genai.GenerativeModel('gemini-1.5-flash-latest')
185
+ response = gemini_model_instance.generate_content(prompt)
186
+
187
+ # Prepare sources text
188
+ sources_text = "--- Sources (Context Chunks) ---\n"
189
+ for i, chunk in enumerate(context_chunks):
190
+ sources_text += f"\n[Source {i+1}]:\n{chunk}\n"
191
+
192
+ return response.text, sources_text # Return answer and sources separately
193
+
194
+ except Exception as e:
195
+ return f"Error generating response: {str(e)}\n{traceback.format_exc()}", "" # Return empty string for sources
196
+
197
+ with gr.Blocks(title="RAG Book Assistant") as demo:
198
+ api_key_state = gr.State(None) # Store the API key
199
+
200
+ gr.Markdown("# 📚 RAG Book Assistant")
201
+ gr.Markdown(
202
+ "Upload a PDF book. You can choose to process the full book or a specific page range. "
203
+ "Processing a new PDF (or range) will **replace the current one**.\n\n"
204
+ )
205
+
206
+ with gr.Row():
207
+ with gr.Column(scale=2):
208
+ with gr.Group() as api_key_group:
209
+ api_key_input = gr.Textbox(label="Gemini API Key", type="password", elem_id="api_key_input_id")
210
+ confirm_api_key_btn = gr.Button("Confirm API Key", elem_id="confirm_api_key_btn_id")
211
+
212
+ api_key_status_output = gr.Markdown(visible=False, value="API Key Set!", elem_id="api_key_status_id")
213
+
214
+ pdf_input = gr.File(label="Upload PDF Book", file_types=['.pdf'])
215
+
216
+ processing_mode_input = gr.Radio(
217
+ label="Processing Mode",
218
+ choices=["Full Book", "Page Range"],
219
+ value="Full Book",
220
+ interactive=True
221
  )
222
+
223
+ with gr.Row(visible=False) as page_range_ui_row:
224
+ start_page_input = gr.Number(label="Start Page", minimum=1, precision=0, interactive=True)
225
+ end_page_input = gr.Number(label="End Page", minimum=1, precision=0, interactive=True)
226
+
227
+ process_btn = gr.Button("Process PDF (Replaces Current Book)")
228
+
229
+ query_input = gr.Textbox(label="Ask a question about the current book", lines=3)
230
+ submit_btn = gr.Button("Submit Question")
231
+
232
+ with gr.Column(scale=1):
233
+ status_output = gr.Textbox(label="Processing Status", interactive=False, lines=5)
234
+ response_output = gr.Textbox(label="Response (Answer)", interactive=False, lines=10)
235
+ sources_output = gr.Textbox(label="Sources (Context Chunks)", interactive=False, lines=10)
236
+
237
+ # Logic to show/hide page range inputs
238
+ def update_page_range_visibility(mode):
239
+ return gr.Row(visible=(mode == "Page Range"))
240
+
241
+ processing_mode_input.change(
242
+ fn=update_page_range_visibility,
243
+ inputs=processing_mode_input,
244
+ outputs=page_range_ui_row
245
+ )
246
+
247
+ # Logic to handle API key confirmation
248
+ def confirm_api_key(api_key):
249
+ if api_key:
250
+ return {
251
+ api_key_state: api_key,
252
+ api_key_group: gr.Group(visible=False),
253
+ api_key_status_output: gr.Markdown(visible=True, value="API Key Set and Hidden.")
254
+ }
255
+ else:
256
+ return {
257
+ api_key_state: None,
258
+ api_key_group: gr.Group(visible=True),
259
+ api_key_status_output: gr.Markdown(visible=True, value="Please enter an API Key.")
260
+ }
261
+
262
+ confirm_api_key_btn.click(
263
+ fn=confirm_api_key,
264
+ inputs=[api_key_input],
265
+ outputs=[api_key_state, api_key_group, api_key_status_output]
266
+ )
267
+
268
+ process_btn.click(
269
+ process_pdf,
270
+ inputs=[pdf_input, processing_mode_input, start_page_input, end_page_input],
271
+ outputs=[status_output]
272
+ )
273
+
274
+ submit_btn.click(
275
+ generate_response,
276
+ inputs=[query_input, api_key_state],
277
+ outputs=[response_output, sources_output]
278
+ )
279
+
280
+ if __name__ == "__main__":
281
+ demo.launch(share=True)