DrishtiSharma commited on
Commit
572dc29
Β·
verified Β·
1 Parent(s): 8a5fc6d

Create test.py

Browse files
Files changed (1) hide show
  1. lab/test.py +360 -0
lab/test.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 (Only Happens Once)
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
+ # ----------------- Query Input -----------------
175
+ query = None
176
+
177
+ # Check if a valid PDF URL has been entered (but not processed yet)
178
+ pdf_url_entered = bool(st.session_state.get("pdf_url")) # Checks if text is in the input box
179
+
180
+ # No PDF Provided Yet
181
+ if not st.session_state.pdf_path and not pdf_url_entered:
182
+ st.info("πŸ“₯ **Please upload a PDF or enter a valid URL to proceed.**")
183
+
184
+ # PDF URL Exists but Not Processed Yet (Only show if URL exists but hasn't been downloaded)
185
+ elif pdf_url_entered and not st.session_state.pdf_loaded:
186
+ st.warning("⚠️ **PDF URL detected! Click 'Download and Process PDF' to proceed.**")
187
+
188
+ # Processing in Progress
189
+ elif st.session_state.get("trigger_download", False) and (
190
+ not st.session_state.pdf_loaded or not st.session_state.chunked or not st.session_state.vector_created
191
+ ):
192
+ st.info("⏳ **Processing your document... Please wait.**")
193
+
194
+ # βœ… Step 4: Processing Complete, Ready for Questions
195
+ elif st.session_state.pdf_loaded and st.session_state.chunked and st.session_state.vector_created:
196
+ st.success("πŸŽ‰ **Processing complete! You can now ask questions.**")
197
+ query = st.text_input("πŸ” **Ask a question about the document:**")
198
+
199
+ if query:
200
+ with st.spinner("πŸ”„ Retrieving relevant context..."):
201
+ retriever = st.session_state.vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 3})
202
+ contexts = retriever.invoke(query)
203
+ # Debugging: Check what was retrieved
204
+ #st.write("Retrieved Contexts:", contexts)
205
+ #st.write("Number of Contexts:", len(contexts)
206
+
207
+ context = [d.page_content for d in contexts]
208
+ # Debugging: Check extracted context
209
+ #st.write("Extracted Context (page_content):", context)
210
+ #st.write("Number of Extracted Contexts:", len(context))
211
+
212
+ st.write("πŸ“„ **Relevant Passages Retrieved:**")
213
+ for idx, doc in enumerate(contexts):
214
+ st.write(f"**Excerpt {idx+1}:** {doc.page_content}")
215
+
216
+
217
+ 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.
218
+ Analyze the provided QUERY AND CONTEXT to determine if each Ccontent in the CONTEXT LIST contains Relevant information to answer the QUERY.
219
+
220
+ Guidelines:
221
+ 1. The content must not introduce new information beyond what's provided in the QUERY.
222
+ 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).
223
+ 3. Be vigilant for subtle misattributions or conflations of information, even if the date or other details are correct.
224
+ 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.
225
+
226
+ Analyze the text thoroughly and assign a relevancy score 0 or 1 where:
227
+ - 0: The content has all the necessary information to answer the QUERY
228
+ - 1: The content does not has the necessary information to answer the QUERY
229
+
230
+
231
+ EXAMPLE:
232
+ INPUT (for context only, not to be used for faithfulness evaluation):
233
+ What is the capital of France?
234
+
235
+ CONTEXT:
236
+ ['France is a country in Western Europe. Its capital is Paris, which is known for landmarks like the Eiffel Tower.',
237
+ 'Mr. Naveen patnaik has been the chief minister of Odisha for consequetive 5 terms']
238
+
239
+ OUTPUT:
240
+ The Context has sufficient information to answer the query.
241
+
242
+ RESPONSE:
243
+ {{"score":0}}
244
+
245
+
246
+ CONTENT LIST:
247
+ {context}
248
+
249
+ QUERY:
250
+ {retriever_query}
251
+ Provide your verdict in JSON format with a single key 'score' and no preamble or explanation:
252
+ [{{"content:1,"score": <your score either 0 or 1>,"Reasoning":<why you have chose the score as 0 or 1>}},
253
+ {{"content:2,"score": <your score either 0 or 1>,"Reasoning":<why you have chose the score as 0 or 1>}},
254
+ ...]
255
+ """
256
+
257
+ context_relevancy_checker_prompt = PromptTemplate(input_variables=["retriever_query","context"],template=relevancy_prompt)
258
+
259
+ relevant_prompt = PromptTemplate(
260
+ input_variables=["relevancy_response"],
261
+ template="""
262
+ Your main task is to analyze the json structure as a part of the Relevancy Response.
263
+ Review the Relevancy Response and do the following:-
264
+ (1) Look at the Json Structure content
265
+ (2) Analyze the 'score' key in the Json Structure content.
266
+ (3) pick the value of 'content' key against those 'score' key value which has 0.
267
+
268
+ Relevancy Response:
269
+ {relevancy_response}
270
+
271
+ Provide your verdict in JSON format with a single key 'content number' and no preamble or explanation:
272
+ [{{"content":<content number>}}]
273
+ """
274
+ )
275
+
276
+ context_prompt = PromptTemplate(
277
+ input_variables=["context_number"],
278
+ template="""
279
+ 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:-
280
+ (1) Look at the output from the Relevant Context Picker Agent.
281
+ (2) Analyze the 'content' key in the Json Structure format({{"content":<<content_number>>}}).
282
+ (3) Retrieve the value of 'content' key and pick up the context corresponding to that element from the Content List provided.
283
+ (4) Pass the retrieved context for each corresponing element number referred in the 'Context Number Response'
284
+
285
+ Context Number Response:
286
+ {context_number}
287
+
288
+ Content List:
289
+ {context}
290
+
291
+ Provide your verdict in JSON format with a two key 'relevant_content' and 'context_number' no preamble or explanation:
292
+ [{{"context_number":<content1>,"relevant_content":<content corresponing to that element 1 in the Content List>}},
293
+ {{"context_number":<content4>,"relevant_content":<content corresponing to that element 4 in the Content List>}},
294
+ ...
295
+ ]
296
+ """
297
+ )
298
+
299
+ 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
300
+ 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'.
301
+
302
+ QUERY:
303
+ {query}
304
+
305
+ CONTEXT
306
+ {context}
307
+
308
+ ANSWER:
309
+ """
310
+
311
+ context_relevancy_evaluation_chain = LLMChain(llm=llm_judge, prompt=context_relevancy_checker_prompt, output_key="relevancy_response")
312
+
313
+ response_crisis = context_relevancy_evaluation_chain.invoke({"context":context,"retriever_query":query})
314
+
315
+ pick_relevant_context_chain = LLMChain(llm=llm_judge, prompt=relevant_prompt, output_key="context_number")
316
+
317
+ relevant_response = pick_relevant_context_chain.invoke({"relevancy_response":response_crisis['relevancy_response']})
318
+
319
+ relevant_contexts_chain = LLMChain(llm=llm_judge, prompt=context_prompt, output_key="relevant_contexts")
320
+
321
+ contexts = relevant_contexts_chain.invoke({"context_number":relevant_response['context_number'],"context":context})
322
+
323
+ final_prompt = PromptTemplate(input_variables=["query","context"],template=rag_prompt)
324
+
325
+ response_chain = LLMChain(llm=rag_llm,prompt=final_prompt,output_key="final_response")
326
+
327
+ response = response_chain.invoke({"query":query,"context":contexts['relevant_contexts']})
328
+
329
+ # Orchestrate using SequentialChain
330
+ context_management_chain = SequentialChain(
331
+ chains=[context_relevancy_evaluation_chain ,pick_relevant_context_chain, relevant_contexts_chain,response_chain],
332
+ input_variables=["context","retriever_query","query"],
333
+ output_variables=["relevancy_response", "context_number","relevant_contexts","final_response"]
334
+ )
335
+
336
+ final_output = context_management_chain({"context":context,"retriever_query":query,"query":query})
337
+
338
+ #st.subheader('final_output["relevancy_response"]')
339
+ #st.write(final_output["relevancy_response"] )
340
+
341
+ st.write("πŸ“Œ **Relevance Analysis:**")
342
+ if isinstance(final_output["relevancy_response"], list):
343
+ for item in final_output["relevancy_response"]:
344
+ st.write(f"βœ… **Context {item.get('content', 'N/A')} - Score: {item.get('score', 'N/A')}**")
345
+ st.write(f"**Reasoning:** {item.get('Reasoning', 'No explanation provided.')}")
346
+ else:
347
+ st.write("⚠️ No relevance analysis available.")
348
+
349
+
350
+ st.subheader('final_output["context_number"]')
351
+ st.write(final_output["context_number"])
352
+
353
+ st.subheader('final_output["relevant_contexts"]')
354
+ st.write(final_output["relevant_contexts"])
355
+
356
+ #st.subheader('final_output["final_response"]')
357
+ #st.write(final_output["final_response"])
358
+
359
+ st.subheader("πŸ“’ **Final Answer:**")
360
+ st.write(final_output["final_response"] if final_output["final_response"] else "⚠️ No clear answer found based on retrieved content.")