Spaces:
Runtime error

Kavi11 commited on
Commit
2ec5a5d
·
verified ·
1 Parent(s): a2dcf81

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +343 -0
app.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File, HTTPException, Form
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydantic import BaseModel, HttpUrl
4
+ from typing import List, Optional
5
+ import requests
6
+ from bs4 import BeautifulSoup
7
+ from langchain_community.document_loaders import PyPDFLoader
8
+ from langchain_text_splitters import CharacterTextSplitter
9
+ from langchain_community.vectorstores import FAISS
10
+ from langchain_community.embeddings import HuggingFaceEmbeddings
11
+ from langchain_core.documents import Document
12
+ from groq import Groq
13
+ import tempfile
14
+ import os
15
+ import uuid
16
+
17
+ # Initialize FastAPI app
18
+ app = FastAPI(
19
+ title="RAG Chatbot API",
20
+ description="FastAPI-based RAG chatbot with PDF and web scraping support",
21
+ version="1.0.0"
22
+ )
23
+
24
+ # Add CORS middleware
25
+ app.add_middleware(
26
+ CORSMiddleware,
27
+ allow_origins=["*"],
28
+ allow_credentials=True,
29
+ allow_methods=["*"],
30
+ allow_headers=["*"],
31
+ )
32
+
33
+ # In-memory storage for vector databases and chat sessions
34
+ sessions = {}
35
+
36
+ # Pydantic models
37
+ class ChatRequest(BaseModel):
38
+ session_id: str
39
+ message: str
40
+ api_key: str
41
+ model: str = "llama-3.1-8b-instant"
42
+
43
+ class ChatResponse(BaseModel):
44
+ session_id: str
45
+ question: str
46
+ answer: str
47
+
48
+ class WebScrapingRequest(BaseModel):
49
+ url: HttpUrl
50
+ session_id: Optional[str] = None
51
+
52
+ class SessionResponse(BaseModel):
53
+ session_id: str
54
+ message: str
55
+ num_chunks: int
56
+ rag_type: str
57
+
58
+ class SessionInfo(BaseModel):
59
+ session_id: str
60
+ rag_type: Optional[str]
61
+ chat_history: List[dict]
62
+ has_vector_db: bool
63
+
64
+ # Helper functions
65
+ def load_embeddings():
66
+ """Load HuggingFace embeddings model"""
67
+ return HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
68
+
69
+ def process_pdf(file_path: str):
70
+ """Process PDF file"""
71
+ try:
72
+ loader = PyPDFLoader(file_path)
73
+ docs = loader.load()
74
+ return docs
75
+ except Exception as e:
76
+ raise HTTPException(status_code=500, detail=f"Error processing PDF: {str(e)}")
77
+
78
+ def create_vector_db(documents, embeddings):
79
+ """Create FAISS vector database from documents"""
80
+ try:
81
+ text_splitter = CharacterTextSplitter(
82
+ chunk_size=1000,
83
+ chunk_overlap=200
84
+ )
85
+ chunks = text_splitter.split_documents(documents)
86
+ vector_db = FAISS.from_documents(chunks, embeddings)
87
+ return vector_db, len(chunks)
88
+ except Exception as e:
89
+ raise HTTPException(status_code=500, detail=f"Error creating vector database: {str(e)}")
90
+
91
+ def scrape_website(url: str):
92
+ """Scrape website content"""
93
+ try:
94
+ response = requests.get(url, timeout=10)
95
+ response.raise_for_status()
96
+
97
+ soup = BeautifulSoup(response.text, "html.parser")
98
+
99
+ texts = []
100
+ for tag in soup.find_all(["p", "li", "a", "td", "h1", "h2", "h3"]):
101
+ text = tag.get_text(strip=True)
102
+ if text and len(text) > 30:
103
+ texts.append(text)
104
+
105
+ full_text = "\n".join(texts)
106
+
107
+ document = Document(
108
+ page_content=full_text,
109
+ metadata={"source": url}
110
+ )
111
+
112
+ return [document]
113
+ except Exception as e:
114
+ raise HTTPException(status_code=500, detail=f"Error scraping website: {str(e)}")
115
+
116
+ def generate_response(message: str, vector_db, api_key: str, model: str):
117
+ """Generate chatbot response using RAG"""
118
+ try:
119
+ # Retrieve relevant chunks
120
+ result = vector_db.similarity_search(message, k=3)
121
+ context = []
122
+ for i in result:
123
+ context.append(f"Chunk: {i.page_content}")
124
+
125
+ # Create Groq client
126
+ client = Groq(api_key=api_key)
127
+
128
+ prompt = """
129
+ You are a smart chatbot. You need to respond to user questions only by referring to the data present within the below knowledge base.
130
+ Don't give any reference to the chunk which you are referring to. Just return a well-structured response as the answer to the user question.
131
+ """
132
+
133
+ finalprompt = f"{prompt}\n\nKnowledge Base: {context}"
134
+
135
+ completion = client.chat.completions.create(
136
+ model=model,
137
+ messages=[
138
+ {
139
+ "role": "system",
140
+ "content": finalprompt
141
+ },
142
+ {
143
+ "role": "user",
144
+ "content": message
145
+ }
146
+ ],
147
+ temperature=0,
148
+ max_completion_tokens=1024
149
+ )
150
+
151
+ return completion.choices[0].message.content
152
+ except Exception as e:
153
+ raise HTTPException(status_code=500, detail=f"Error generating response: {str(e)}")
154
+
155
+ # API Endpoints
156
+ @app.get("/")
157
+ async def root():
158
+ return {
159
+ "message": "RAG Chatbot API",
160
+ "version": "1.0.0",
161
+ "endpoints": {
162
+ "POST /session/create": "Create a new session",
163
+ "POST /upload/pdf": "Upload and process PDF",
164
+ "POST /scrape/web": "Scrape website content",
165
+ "POST /chat": "Send a chat message",
166
+ "GET /session/{session_id}": "Get session info",
167
+ "DELETE /session/{session_id}": "Delete a session"
168
+ }
169
+ }
170
+
171
+ @app.post("/session/create")
172
+ async def create_session():
173
+ """Create a new chat session"""
174
+ session_id = str(uuid.uuid4())
175
+ sessions[session_id] = {
176
+ "vector_db": None,
177
+ "chat_history": [],
178
+ "rag_type": None
179
+ }
180
+ return {"session_id": session_id, "message": "Session created successfully"}
181
+
182
+ @app.post("/upload/pdf", response_model=SessionResponse)
183
+ async def upload_pdf(
184
+ file: UploadFile = File(...),
185
+ session_id: Optional[str] = Form(None)
186
+ ):
187
+ """Upload and process a PDF file"""
188
+ # Create session if not provided
189
+ if not session_id:
190
+ session_id = str(uuid.uuid4())
191
+ sessions[session_id] = {
192
+ "vector_db": None,
193
+ "chat_history": [],
194
+ "rag_type": None
195
+ }
196
+
197
+ if session_id not in sessions:
198
+ raise HTTPException(status_code=404, detail="Session not found")
199
+
200
+ # Validate file type
201
+ if not file.filename.endswith('.pdf'):
202
+ raise HTTPException(status_code=400, detail="Only PDF files are supported")
203
+
204
+ # Save uploaded file temporarily
205
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
206
+ content = await file.read()
207
+ tmp_file.write(content)
208
+ tmp_path = tmp_file.name
209
+
210
+ try:
211
+ # Load embeddings
212
+ embeddings = load_embeddings()
213
+
214
+ # Process PDF
215
+ docs = process_pdf(tmp_path)
216
+
217
+ # Create vector database
218
+ vector_db, num_chunks = create_vector_db(docs, embeddings)
219
+
220
+ # Store in session
221
+ sessions[session_id]["vector_db"] = vector_db
222
+ sessions[session_id]["rag_type"] = "PDF"
223
+ sessions[session_id]["chat_history"] = []
224
+
225
+ return SessionResponse(
226
+ session_id=session_id,
227
+ message="PDF processed successfully",
228
+ num_chunks=num_chunks,
229
+ rag_type="PDF"
230
+ )
231
+ finally:
232
+ # Clean up temp file
233
+ os.unlink(tmp_path)
234
+
235
+ @app.post("/scrape/web", response_model=SessionResponse)
236
+ async def scrape_web(request: WebScrapingRequest):
237
+ """Scrape website and create vector database"""
238
+ # Create session if not provided
239
+ session_id = request.session_id or str(uuid.uuid4())
240
+
241
+ if session_id not in sessions:
242
+ sessions[session_id] = {
243
+ "vector_db": None,
244
+ "chat_history": [],
245
+ "rag_type": None
246
+ }
247
+
248
+ # Load embeddings
249
+ embeddings = load_embeddings()
250
+
251
+ # Scrape website
252
+ documents = scrape_website(str(request.url))
253
+
254
+ # Create vector database
255
+ vector_db, num_chunks = create_vector_db(documents, embeddings)
256
+
257
+ # Store in session
258
+ sessions[session_id]["vector_db"] = vector_db
259
+ sessions[session_id]["rag_type"] = "Web"
260
+ sessions[session_id]["chat_history"] = []
261
+
262
+ return SessionResponse(
263
+ session_id=session_id,
264
+ message="Website scraped successfully",
265
+ num_chunks=num_chunks,
266
+ rag_type="Web"
267
+ )
268
+
269
+ @app.post("/chat", response_model=ChatResponse)
270
+ async def chat(request: ChatRequest):
271
+ """Send a chat message and get a response"""
272
+ if request.session_id not in sessions:
273
+ raise HTTPException(status_code=404, detail="Session not found")
274
+
275
+ session = sessions[request.session_id]
276
+
277
+ if session["vector_db"] is None:
278
+ raise HTTPException(
279
+ status_code=400,
280
+ detail="No knowledge base loaded. Please upload a PDF or scrape a website first."
281
+ )
282
+
283
+ # Generate response
284
+ answer = generate_response(
285
+ request.message,
286
+ session["vector_db"],
287
+ request.api_key,
288
+ request.model
289
+ )
290
+
291
+ # Store in chat history
292
+ chat_entry = {
293
+ "question": request.message,
294
+ "answer": answer
295
+ }
296
+ session["chat_history"].append(chat_entry)
297
+
298
+ return ChatResponse(
299
+ session_id=request.session_id,
300
+ question=request.message,
301
+ answer=answer
302
+ )
303
+
304
+ @app.get("/session/{session_id}", response_model=SessionInfo)
305
+ async def get_session(session_id: str):
306
+ """Get session information"""
307
+ if session_id not in sessions:
308
+ raise HTTPException(status_code=404, detail="Session not found")
309
+
310
+ session = sessions[session_id]
311
+
312
+ return SessionInfo(
313
+ session_id=session_id,
314
+ rag_type=session["rag_type"],
315
+ chat_history=session["chat_history"],
316
+ has_vector_db=session["vector_db"] is not None
317
+ )
318
+
319
+ @app.delete("/session/{session_id}")
320
+ async def delete_session(session_id: str):
321
+ """Delete a session"""
322
+ if session_id not in sessions:
323
+ raise HTTPException(status_code=404, detail="Session not found")
324
+
325
+ del sessions[session_id]
326
+ return {"message": "Session deleted successfully"}
327
+
328
+ @app.get("/sessions")
329
+ async def list_sessions():
330
+ """List all active sessions"""
331
+ session_list = []
332
+ for session_id, data in sessions.items():
333
+ session_list.append({
334
+ "session_id": session_id,
335
+ "rag_type": data["rag_type"],
336
+ "has_vector_db": data["vector_db"] is not None,
337
+ "chat_count": len(data["chat_history"])
338
+ })
339
+ return {"sessions": session_list}
340
+
341
+ if __name__ == "__main__":
342
+ import uvicorn
343
+ uvicorn.run(app, host="0.0.0.0", port=8000)