Arjuu commited on
Commit
f43c1c2
Β·
verified Β·
1 Parent(s): ad7b156

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +303 -0
app.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Personal_AI_Researcher.ipynb
3
+ Automatically generated by Colab.
4
+ Original file is located at
5
+ https://colab.research.google.com/github/Arjun941/RAG-Research-Assistant/blob/main/Personal_AI_Researcher.ipynb
6
+ """
7
+
8
+ import os
9
+ from typing import List, Dict, Any, Optional, TypedDict
10
+
11
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
12
+ from langchain_community.document_loaders import PyPDFLoader
13
+ from langchain_community.vectorstores import Chroma
14
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
15
+ from langchain.prompts import ChatPromptTemplate
16
+
17
+ from langgraph.graph import StateGraph, END
18
+ from langgraph.checkpoint.memory import MemorySaver
19
+
20
+ import chromadb
21
+ import gradio as gr
22
+
23
+ GOOGLE_API_KEY = "AIzaSyDERyKbxN9Da7eMfkO0zw3b4-qCH715h24"
24
+ os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
25
+
26
+ class AgentState(TypedDict):
27
+ query: str
28
+ documents: List[Dict[str, Any]]
29
+ context: str
30
+ answer: str
31
+ sources: List[str]
32
+ error: Optional[str]
33
+
34
+ class ResearchAgent:
35
+ def __init__(self, api_key):
36
+ self.api_key = api_key
37
+
38
+ self.chroma_client = chromadb.PersistentClient(path="./chroma_db")
39
+
40
+ try:
41
+ self.collection = self.chroma_client.get_collection(name="docs")
42
+ except:
43
+ self.collection = self.chroma_client.create_collection(name="docs")
44
+
45
+ self.embeddings = GoogleGenerativeAIEmbeddings(
46
+ model="models/text-embedding-004",
47
+ google_api_key=self.api_key
48
+ )
49
+
50
+ self.llm = ChatGoogleGenerativeAI(
51
+ model="gemini-1.5-flash",
52
+ google_api_key=self.api_key,
53
+ temperature=0.1
54
+ )
55
+
56
+ self.vector_store = Chroma(
57
+ client=self.chroma_client,
58
+ collection_name="docs",
59
+ embedding_function=self.embeddings
60
+ )
61
+
62
+ self.documents = []
63
+ self.setup_workflow()
64
+
65
+ def setup_workflow(self):
66
+ def retrieve_docs(state):
67
+ query = state["query"]
68
+ docs = self.vector_store.similarity_search(query, k=5)
69
+
70
+ context_parts = []
71
+ sources = []
72
+
73
+ for doc in docs:
74
+ context_parts.append(doc.page_content)
75
+ source = f"πŸ“„ {doc.metadata.get('source', 'Unknown')} (Page {doc.metadata.get('page', '?')})"
76
+ if source not in sources:
77
+ sources.append(source)
78
+
79
+ context = "\n\n".join(context_parts)
80
+
81
+ return {
82
+ **state,
83
+ "context": context,
84
+ "sources": sources,
85
+ "documents": [{"content": doc.page_content, "metadata": doc.metadata} for doc in docs]
86
+ }
87
+
88
+ def make_answer(state):
89
+ query = state["query"]
90
+ context = state["context"]
91
+
92
+ if not context:
93
+ return {
94
+ **state,
95
+ "answer": "No documents found. Upload some PDFs first."
96
+ }
97
+
98
+ prompt = ChatPromptTemplate.from_messages([
99
+ ("system", "Answer based on the context: {context}"),
100
+ ("human", "{question}")
101
+ ])
102
+
103
+ chain = prompt | self.llm
104
+ response = chain.invoke({"context": context, "question": query})
105
+
106
+ return {**state, "answer": response.content}
107
+
108
+ def check_docs(state):
109
+ if not self.documents:
110
+ return {
111
+ **state,
112
+ "answer": "No documents uploaded yet. Please upload PDFs first.",
113
+ "sources": []
114
+ }
115
+ return state
116
+
117
+ def continue_or_end(state):
118
+ if not self.documents:
119
+ return "end"
120
+ return "retrieve"
121
+
122
+ workflow = StateGraph(AgentState)
123
+
124
+ workflow.add_node("check", check_docs)
125
+ workflow.add_node("retrieve", retrieve_docs)
126
+ workflow.add_node("generate", make_answer)
127
+
128
+ workflow.set_entry_point("check")
129
+
130
+ workflow.add_conditional_edges(
131
+ "check",
132
+ continue_or_end,
133
+ {
134
+ "end": END,
135
+ "retrieve": "retrieve"
136
+ }
137
+ )
138
+
139
+ workflow.add_edge("retrieve", "generate")
140
+ workflow.add_edge("generate", END)
141
+
142
+ memory = MemorySaver()
143
+ self.workflow = workflow.compile(checkpointer=memory)
144
+
145
+ def add_pdf(self, pdf_path):
146
+ try:
147
+ loader = PyPDFLoader(pdf_path)
148
+ pages = loader.load()
149
+
150
+ text_splitter = RecursiveCharacterTextSplitter(
151
+ chunk_size=1024,
152
+ chunk_overlap=200,
153
+ )
154
+
155
+ documents = []
156
+ for page in pages:
157
+ chunks = text_splitter.split_documents([page])
158
+ for chunk in chunks:
159
+ chunk.metadata.update({
160
+ "source": os.path.basename(pdf_path),
161
+ "file_path": pdf_path
162
+ })
163
+ documents.append(chunk)
164
+
165
+ if documents:
166
+ self.vector_store.add_documents(documents)
167
+ self.documents.extend(documents)
168
+ return f"βœ… Added {len(documents)} chunks from {os.path.basename(pdf_path)}"
169
+ else:
170
+ return f"⚠️ No content found in {os.path.basename(pdf_path)}"
171
+
172
+ except Exception as e:
173
+ return f"Error: {str(e)}"
174
+
175
+ def ask_question(self, question):
176
+ try:
177
+ state = {
178
+ "query": question,
179
+ "documents": [],
180
+ "context": "",
181
+ "answer": "",
182
+ "sources": [],
183
+ "error": None
184
+ }
185
+
186
+ config = {"configurable": {"thread_id": "main"}}
187
+ result = self.workflow.invoke(state, config)
188
+
189
+ return result["answer"], result.get("sources", [])
190
+
191
+ except Exception as e:
192
+ return f"Error: {str(e)}", []
193
+
194
+ def get_stats(self):
195
+ if not self.documents:
196
+ return "No documents loaded."
197
+
198
+ source_counts = {}
199
+ for doc in self.documents:
200
+ source = doc.metadata.get('source', 'Unknown')
201
+ source_counts[source] = source_counts.get(source, 0) + 1
202
+
203
+ stats = f"πŸ“Š Total chunks: {len(self.documents)}\n"
204
+ stats += f"πŸ“ Total files: {len(source_counts)}\n\n"
205
+ for source, count in source_counts.items():
206
+ stats += f"- {source}: {count} chunks\n"
207
+
208
+ return stats
209
+
210
+ agent = ResearchAgent(GOOGLE_API_KEY)
211
+ print("βœ… Agent created!")
212
+
213
+ def upload_file(file):
214
+ if file is None:
215
+ return "❌ No file selected.", ""
216
+
217
+ result = agent.add_pdf(file.name)
218
+ stats = agent.get_stats()
219
+ return result, stats
220
+
221
+ def ask_question_ui(question, history):
222
+ if not question.strip():
223
+ return history
224
+
225
+ answer, sources = agent.ask_question(question)
226
+
227
+ formatted_answer = answer
228
+ if sources:
229
+ formatted_answer += "\n\n**Sources:**\n" + "\n".join(sources)
230
+
231
+ history.append([question, formatted_answer])
232
+ return history
233
+
234
+ def clear_history():
235
+ return []
236
+
237
+ with gr.Blocks() as demo:
238
+ gr.Markdown("# πŸ”¬ PDF Research Assistant")
239
+
240
+ with gr.Tab("πŸ“ Upload Files"):
241
+ with gr.Row():
242
+ with gr.Column():
243
+ file_upload = gr.File(
244
+ label="Choose PDF File",
245
+ file_types=[".pdf"],
246
+ type="filepath"
247
+ )
248
+ upload_btn = gr.Button("Upload PDF")
249
+
250
+ with gr.Column():
251
+ upload_status = gr.Textbox(
252
+ label="Status",
253
+ interactive=False,
254
+ max_lines=3
255
+ )
256
+
257
+ doc_stats = gr.Markdown("No files uploaded yet.")
258
+
259
+ upload_btn.click(
260
+ upload_file,
261
+ inputs=[file_upload],
262
+ outputs=[upload_status, doc_stats]
263
+ )
264
+
265
+ with gr.Tab("πŸ’¬ Ask Questions"):
266
+ chatbot = gr.Chatbot(
267
+ label="Chat with your documents",
268
+ height=400
269
+ )
270
+
271
+ with gr.Row():
272
+ question_input = gr.Textbox(
273
+ label="Your Question",
274
+ placeholder="Ask something about your PDFs...",
275
+ scale=4
276
+ )
277
+ ask_btn = gr.Button("Ask", variant="primary", scale=1)
278
+
279
+ clear_btn = gr.Button("Clear Chat")
280
+
281
+ ask_btn.click(
282
+ ask_question_ui,
283
+ inputs=[question_input, chatbot],
284
+ outputs=[chatbot]
285
+ ).then(
286
+ lambda: "",
287
+ outputs=[question_input]
288
+ )
289
+
290
+ question_input.submit(
291
+ ask_question_ui,
292
+ inputs=[question_input, chatbot],
293
+ outputs=[chatbot]
294
+ ).then(
295
+ lambda: "",
296
+ outputs=[question_input]
297
+ )
298
+
299
+ clear_btn.click(clear_history, outputs=[chatbot])
300
+
301
+ demo.launch(share=True)
302
+
303
+ !gradio deploy