DrishtiSharma commited on
Commit
46f14ac
Β·
verified Β·
1 Parent(s): fbb4cec

Create temp.py

Browse files
Files changed (1) hide show
  1. lab/temp.py +345 -0
lab/temp.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import streamlit as st
4
+ import pickle
5
+ from langchain.chains import LLMChain
6
+ from langchain.prompts import PromptTemplate
7
+ from langchain_groq import ChatGroq
8
+ from langchain.document_loaders import PDFPlumberLoader
9
+ from langchain_experimental.text_splitter import SemanticChunker
10
+ from langchain_huggingface import HuggingFaceEmbeddings
11
+ from langchain_chroma import Chroma
12
+ from langchain.chains import SequentialChain, LLMChain
13
+
14
+ # Set API Keys
15
+ os.environ["GROQ_API_KEY"] = st.secrets.get("GROQ_API_KEY", "")
16
+
17
+ # Load LLM models
18
+ llm_judge = ChatGroq(model="deepseek-r1-distill-llama-70b")
19
+ rag_llm = ChatGroq(model="mixtral-8x7b-32768")
20
+
21
+ llm_judge.verbose = True
22
+ rag_llm.verbose = True
23
+
24
+ VECTOR_DB_PATH = "/tmp/chroma_db"
25
+ CHUNKS_FILE = "/tmp/chunks.pkl"
26
+
27
+ # Session State Initialization
28
+ if "vector_store" not in st.session_state:
29
+ st.session_state.vector_store = None
30
+ if "documents" not in st.session_state:
31
+ st.session_state.documents = None
32
+ if "pdf_path" not in st.session_state:
33
+ st.session_state.pdf_path = None
34
+ if "pdf_loaded" not in st.session_state:
35
+ st.session_state.pdf_loaded = False
36
+ if "chunked" not in st.session_state:
37
+ st.session_state.chunked = False
38
+ if "vector_created" not in st.session_state:
39
+ st.session_state.vector_created = False
40
+
41
+ st.title("Blah-2")
42
+
43
+ # Step 1: Choose PDF Source
44
+ pdf_source = st.radio("Upload or provide a link to a PDF:", ["Enter a PDF URL", "Upload a PDF file"], index=0, horizontal=True)
45
+
46
+ if pdf_source == "Upload a PDF file":
47
+ uploaded_file = st.file_uploader("Upload your PDF file", type="pdf")
48
+ if uploaded_file:
49
+ st.session_state.pdf_path = "temp.pdf"
50
+ with open(st.session_state.pdf_path, "wb") as f:
51
+ f.write(uploaded_file.getbuffer())
52
+ st.session_state.pdf_loaded = False
53
+ st.session_state.chunked = False
54
+ st.session_state.vector_created = False
55
+
56
+ elif pdf_source == "Enter a PDF URL":
57
+ pdf_url = st.text_input("Enter PDF URL:", value="https://arxiv.org/pdf/2406.06998", key="pdf_url", on_change=lambda: st.session_state.update(trigger_download=True))
58
+
59
+ # Button OR Enter key will trigger download
60
+ if st.button("Download and Process PDF") or st.session_state.get("trigger_download", False):
61
+ with st.spinner("Downloading PDF..."):
62
+ try:
63
+ response = requests.get(pdf_url)
64
+ if response.status_code == 200:
65
+ st.session_state.pdf_path = "temp.pdf"
66
+ with open(st.session_state.pdf_path, "wb") as f:
67
+ f.write(response.content)
68
+
69
+ # Reset states
70
+ st.session_state.pdf_loaded = False
71
+ st.session_state.chunked = False
72
+ st.session_state.vector_created = False
73
+ st.session_state.trigger_download = False # Reset trigger
74
+
75
+ st.success("βœ… PDF Downloaded Successfully!")
76
+ else:
77
+ st.error("❌ Failed to download PDF. Check the URL.")
78
+ except Exception as e:
79
+ st.error(f"❌ Error downloading PDF: {e}")
80
+
81
+
82
+ # Step 2: Load & Process PDF (Only Once)
83
+ if st.session_state.pdf_path and not st.session_state.pdf_loaded:
84
+ with st.spinner("Loading PDF..."):
85
+ try:
86
+ loader = PDFPlumberLoader(st.session_state.pdf_path)
87
+ docs = loader.load()
88
+ st.session_state.documents = docs
89
+ st.session_state.pdf_loaded = True
90
+ st.success(f"βœ… **PDF Loaded!** Total Pages: {len(docs)}")
91
+ except Exception as e:
92
+ st.error(f"❌ Error processing PDF: {e}")
93
+
94
+ # Load Cached Chunks if Available
95
+ def load_chunks():
96
+ if os.path.exists(CHUNKS_FILE):
97
+ with open(CHUNKS_FILE, "rb") as f:
98
+ return pickle.load(f)
99
+ return None
100
+
101
+ if not st.session_state.chunked: # Ensure chunking only happens once
102
+ cached_chunks = load_chunks()
103
+ if cached_chunks:
104
+ st.session_state.documents = cached_chunks
105
+ st.session_state.chunked = True
106
+
107
+ # Step 3: Chunking
108
+ if st.session_state.pdf_loaded and not st.session_state.chunked:
109
+ with st.spinner("Chunking the document..."):
110
+ try:
111
+ model_name = "nomic-ai/modernbert-embed-base"
112
+ embedding_model = HuggingFaceEmbeddings(model_name=model_name, model_kwargs={'device': 'cpu'})
113
+ text_splitter = SemanticChunker(embedding_model)
114
+
115
+ if st.session_state.documents:
116
+ documents = text_splitter.split_documents(st.session_state.documents)
117
+ st.session_state.documents = documents
118
+ st.session_state.chunked = True
119
+
120
+ # Save chunks for persistence
121
+ with open(CHUNKS_FILE, "wb") as f:
122
+ pickle.dump(documents, f)
123
+
124
+ st.success(f"βœ… **Document Chunked!** Total Chunks: {len(documents)}")
125
+ except Exception as e:
126
+ st.error(f"❌ Error chunking document: {e}")
127
+
128
+ # Step 4: Setup Vectorstore
129
+ def load_vector_store():
130
+ return Chroma(persist_directory=VECTOR_DB_PATH, collection_name="deepseek_collection", embedding_function=HuggingFaceEmbeddings(model_name="nomic-ai/modernbert-embed-base"))
131
+
132
+ if st.session_state.chunked and not st.session_state.vector_created:
133
+ with st.spinner("Creating vector store..."):
134
+ try:
135
+ if st.session_state.vector_store is None: # Prevent unnecessary reloading
136
+ st.session_state.vector_store = load_vector_store()
137
+
138
+ if len(st.session_state.vector_store.get()["documents"]) == 0: # Prevent duplicate insertions
139
+ st.session_state.vector_store.add_documents(st.session_state.documents)
140
+
141
+ num_documents = len(st.session_state.vector_store.get()["documents"])
142
+ st.session_state.vector_created = True
143
+ st.success(f"βœ… **Vector Store Created!** Total documents stored: {num_documents}")
144
+ except Exception as e:
145
+ st.error(f"❌ Error creating vector store: {e}")
146
+
147
+ # Debugging Logs
148
+ #st.write("πŸ“„ **PDF Loaded:**", st.session_state.pdf_loaded)
149
+ #st.write("πŸ”Ή **Chunked:**", st.session_state.chunked)
150
+ #st.write("πŸ“‚ **Vector Store Created:**", st.session_state.vector_created)
151
+
152
+
153
+ # ----------------- Query Input -----------------
154
+ query = None
155
+
156
+ # Check if a valid PDF URL has been entered (but not processed yet)
157
+ pdf_url_entered = bool(st.session_state.get("pdf_url")) # Checks if text is in the input box
158
+
159
+ # No PDF Provided Yet
160
+ if not st.session_state.pdf_path and not pdf_url_entered:
161
+ st.info("πŸ“₯ **Please upload a PDF or enter a valid URL to proceed.**")
162
+
163
+ # PDF URL Exists but Not Processed Yet (Only show if URL exists but hasn't been downloaded)
164
+ elif pdf_url_entered and not st.session_state.pdf_loaded:
165
+ st.warning("⚠️ **PDF URL detected! Click 'Download and Process PDF' to proceed.**")
166
+
167
+ # Processing in Progress
168
+ elif st.session_state.get("trigger_download", False) and (
169
+ not st.session_state.pdf_loaded or not st.session_state.chunked or not st.session_state.vector_created
170
+ ):
171
+ st.info("⏳ **Processing your document... Please wait.**")
172
+
173
+ # βœ… Step 4: Processing Complete, Ready for Questions
174
+ elif st.session_state.pdf_loaded and st.session_state.chunked and st.session_state.vector_created:
175
+ st.success("πŸŽ‰ **Processing complete! You can now ask questions.**")
176
+ query = st.text_input("πŸ” **Ask a question about the document:**")
177
+
178
+ if query:
179
+ with st.spinner("πŸ”„ Retrieving relevant context..."):
180
+ retriever = st.session_state.vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 3})
181
+ contexts = retriever.invoke(query)
182
+ # Debugging: Check what was retrieved
183
+ #st.write("Retrieved Contexts:", contexts)
184
+ #st.write("Number of Contexts:", len(contexts)
185
+
186
+ context = [d.page_content for d in contexts]
187
+ # Debugging: Check extracted context
188
+ #st.write("Extracted Context (page_content):", context)
189
+ #st.write("Number of Extracted Contexts:", len(context))
190
+
191
+ #st.write("πŸ“„ **Relevant Passages Retrieved:**")
192
+ #for idx, doc in enumerate(contexts):
193
+ #st.write(f"**Excerpt {idx+1}:** {doc.page_content}")
194
+
195
+
196
+ relevancy_prompt = """You are an expert judge tasked with evaluating whether the EACH OF THE CONTEXT provided in the CONTEXT LIST is self sufficient to answer the QUERY asked.
197
+ Analyze the provided QUERY AND CONTEXT to determine if each Ccontent in the CONTEXT LIST contains Relevant information to answer the QUERY.
198
+
199
+ Guidelines:
200
+ 1. The content must not introduce new information beyond what's provided in the QUERY.
201
+ 2. Pay close attention to the subject of statements. Ensure that attributes, actions, or dates are correctly associated with the right entities (e.g., a person vs. a TV show they star in).
202
+ 3. Be vigilant for subtle misattributions or conflations of information, even if the date or other details are correct.
203
+ 4. Check that the content in the CONTEXT LIST doesn't oversimplify or generalize information in a way that changes the meaning of the QUERY.
204
+
205
+ Analyze the text thoroughly and assign a relevancy score 0 or 1 where:
206
+ - 0: The content has all the necessary information to answer the QUERY
207
+ - 1: The content does not has the necessary information to answer the QUERY
208
+
209
+ ```
210
+ EXAMPLE:
211
+ INPUT (for context only, not to be used for faithfulness evaluation):
212
+ What is the capital of France?
213
+
214
+ CONTEXT:
215
+ ['France is a country in Western Europe. Its capital is Paris, which is known for landmarks like the Eiffel Tower.',
216
+ 'Mr. Naveen patnaik has been the chief minister of Odisha for consequetive 5 terms']
217
+
218
+ OUTPUT:
219
+ The Context has sufficient information to answer the query.
220
+
221
+ RESPONSE:
222
+ {{"score":0}}
223
+ ```
224
+
225
+ CONTENT LIST:
226
+ {context}
227
+
228
+ QUERY:
229
+ {retriever_query}
230
+ Provide your verdict in JSON format with a single key 'score' and no preamble or explanation:
231
+ [{{"content:1,"score": <your score either 0 or 1>,"Reasoning":<why you have chose the score as 0 or 1>}},
232
+ {{"content:2,"score": <your score either 0 or 1>,"Reasoning":<why you have chose the score as 0 or 1>}},
233
+ ...]
234
+ """
235
+
236
+ context_relevancy_checker_prompt = PromptTemplate(input_variables=["retriever_query","context"],template=relevancy_prompt)
237
+
238
+ relevant_prompt = PromptTemplate(
239
+ input_variables=["relevancy_response"],
240
+ template="""
241
+ Your main task is to analyze the json structure as a part of the Relevancy Response.
242
+ Review the Relevancy Response and do the following:-
243
+ (1) Look at the Json Structure content
244
+ (2) Analyze the 'score' key in the Json Structure content.
245
+ (3) pick the value of 'content' key against those 'score' key value which has 0.
246
+
247
+ Relevancy Response:
248
+ {relevancy_response}
249
+
250
+ Provide your verdict in JSON format with a single key 'content number' and no preamble or explanation:
251
+ [{{"content":<content number>}}]
252
+ """
253
+ )
254
+
255
+ context_prompt = PromptTemplate(
256
+ input_variables=["context_number"],
257
+ template="""
258
+ Your main task is to analyze the json structure as a part of the Context Number Response and the list of Contexts provided in the 'Content List' and perform the following steps:-
259
+ (1) Look at the output from the Relevant Context Picker Agent.
260
+ (2) Analyze the 'content' key in the Json Structure format({{"content":<<content_number>>}}).
261
+ (3) Retrieve the value of 'content' key and pick up the context corresponding to that element from the Content List provided.
262
+ (4) Pass the retrieved context for each corresponing element number referred in the 'Context Number Response'
263
+
264
+ Context Number Response:
265
+ {context_number}
266
+
267
+ Content List:
268
+ {context}
269
+
270
+ Provide your verdict in JSON format with a two key 'relevant_content' and 'context_number' no preamble or explanation:
271
+ [{{"context_number":<content1>,"relevant_content":<content corresponing to that element 1 in the Content List>}},
272
+ {{"context_number":<content4>,"relevant_content":<content corresponing to that element 4 in the Content List>}},
273
+ ...
274
+ ]
275
+ """
276
+ )
277
+
278
+ rag_prompt = """ You are a helpful assistant very profiient in formulating clear and meaningful answers from the context provided.Based on the CONTEXT Provided ,Please formulate
279
+ a clear concise and meaningful answer for the QUERY asked.Please refrain from making up your own answer in case the COTEXT provided is not sufficient to answer the QUERY.In such a situation please respond as 'I do not know'.
280
+
281
+ QUERY:
282
+ {query}
283
+
284
+ CONTEXT
285
+ {context}
286
+
287
+ ANSWER:
288
+ """
289
+
290
+ context_relevancy_evaluation_chain = LLMChain(llm=llm_judge, prompt=context_relevancy_checker_prompt, output_key="relevancy_response")
291
+
292
+ response_crisis = context_relevancy_evaluation_chain.invoke({"context":context,"retriever_query":query})
293
+
294
+ pick_relevant_context_chain = LLMChain(llm=llm_judge, prompt=relevant_prompt, output_key="context_number")
295
+
296
+ relevant_response = pick_relevant_context_chain.invoke({"relevancy_response":response_crisis['relevancy_response']})
297
+
298
+ relevant_contexts_chain = LLMChain(llm=llm_judge, prompt=context_prompt, output_key="relevant_contexts")
299
+
300
+ contexts = relevant_contexts_chain.invoke({"context_number":relevant_response['context_number'],"context":context})
301
+
302
+ final_prompt = PromptTemplate(input_variables=["query","context"],template=rag_prompt)
303
+
304
+ response_chain = LLMChain(llm=rag_llm,prompt=final_prompt,output_key="final_response")
305
+
306
+ response = response_chain.invoke({"query":query,"context":contexts['relevant_contexts']})
307
+
308
+ # Orchestrate using SequentialChain
309
+ context_management_chain = SequentialChain(
310
+ chains=[context_relevancy_evaluation_chain ,pick_relevant_context_chain, relevant_contexts_chain,response_chain],
311
+ input_variables=["context","retriever_query","query"],
312
+ output_variables=["relevancy_response", "context_number","relevant_contexts","final_response"]
313
+ )
314
+
315
+ final_output = context_management_chain({"context":context,"retriever_query":query,"query":query})
316
+
317
+ #st.subheader('final_output["relevancy_response"]')
318
+ #st.write(final_output["relevancy_response"] )
319
+
320
+
321
+ st.markdown("## πŸ’‘ **Final Answer:**")
322
+ st.success(final_output["final_response"] if final_output["final_response"] else "⚠️ No clear answer found based on retrieved content.")
323
+
324
+ # πŸ“‚ Expand for Details
325
+ with st.expander("πŸ“– **View Detailed Processing (Relevance, Retrieved Contexts, Analysis)**"):
326
+ # πŸ“Œ Relevance Analysis
327
+ st.markdown("### πŸ“Œ **Relevance Analysis**")
328
+ if isinstance(final_output["relevancy_response"], list):
329
+ for item in final_output["relevancy_response"]:
330
+ st.write(f"βœ… **Context {item.get('content', 'N/A')} - Score: {item.get('score', 'N/A')}**")
331
+ st.write(f"**Reasoning:** {item.get('Reasoning', 'No explanation provided.')}")
332
+ else:
333
+ st.warning("⚠️ No relevance analysis available.")
334
+
335
+ # πŸ“š Retrieved Contexts
336
+ st.markdown("### πŸ“š **Retrieved Contexts**")
337
+ if isinstance(final_output["relevant_contexts"], list):
338
+ for idx, doc in enumerate(final_output["relevant_contexts"], 1):
339
+ st.write(f"πŸ”Ή **Context {idx}:** {doc}")
340
+ else:
341
+ st.warning("⚠️ No retrieved context available.")
342
+
343
+ # πŸ” Retrieved Context Numbers
344
+ st.markdown("### πŸ” **Relevant Context Numbers**")
345
+ st.write(final_output["context_number"])