Spaces:
Runtime error
Runtime error
Download app.py from Kavi11/test-deployment: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/spaces/Kavi11/test-deployment/resolve/main/app.py
- Command line
-
hf download hf://spaces/Kavi11/test-deployment/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Kavi11/test-deployment/resolve/main/app.py
10.8 kB
| from fastapi import FastAPI, UploadFile, File, HTTPException, Form | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel, HttpUrl | |
| from typing import List, Optional | |
| import requests | |
| from bs4 import BeautifulSoup | |
| from langchain_community.document_loaders import PyPDFLoader | |
| from langchain_text_splitters import CharacterTextSplitter | |
| from langchain_community.vectorstores import FAISS | |
| from langchain_community.embeddings import HuggingFaceEmbeddings | |
| from langchain_core.documents import Document | |
| from groq import Groq | |
| import tempfile | |
| import os | |
| import uuid | |
| # Initialize FastAPI app | |
| app = FastAPI( | |
| title="RAG Chatbot API", | |
| description="FastAPI-based RAG chatbot with PDF and web scraping support", | |
| version="1.0.0" | |
| ) | |
| # Add CORS middleware | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # In-memory storage for vector databases and chat sessions | |
| sessions = {} | |
| # Pydantic models | |
| class ChatRequest(BaseModel): | |
| session_id: str | |
| message: str | |
| api_key: str | |
| model: str = "llama-3.1-8b-instant" | |
| class ChatResponse(BaseModel): | |
| session_id: str | |
| question: str | |
| answer: str | |
| class WebScrapingRequest(BaseModel): | |
| url: HttpUrl | |
| session_id: Optional[str] = None | |
| class SessionResponse(BaseModel): | |
| session_id: str | |
| message: str | |
| num_chunks: int | |
| rag_type: str | |
| class SessionInfo(BaseModel): | |
| session_id: str | |
| rag_type: Optional[str] | |
| chat_history: List[dict] | |
| has_vector_db: bool | |
| # Helper functions | |
| def load_embeddings(): | |
| """Load HuggingFace embeddings model""" | |
| return HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2") | |
| def process_pdf(file_path: str): | |
| """Process PDF file""" | |
| try: | |
| loader = PyPDFLoader(file_path) | |
| docs = loader.load() | |
| return docs | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Error processing PDF: {str(e)}") | |
| def create_vector_db(documents, embeddings): | |
| """Create FAISS vector database from documents""" | |
| try: | |
| text_splitter = CharacterTextSplitter( | |
| chunk_size=1000, | |
| chunk_overlap=200 | |
| ) | |
| chunks = text_splitter.split_documents(documents) | |
| vector_db = FAISS.from_documents(chunks, embeddings) | |
| return vector_db, len(chunks) | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Error creating vector database: {str(e)}") | |
| def scrape_website(url: str): | |
| """Scrape website content""" | |
| try: | |
| response = requests.get(url, timeout=10) | |
| response.raise_for_status() | |
| soup = BeautifulSoup(response.text, "html.parser") | |
| texts = [] | |
| for tag in soup.find_all(["p", "li", "a", "td", "h1", "h2", "h3"]): | |
| text = tag.get_text(strip=True) | |
| if text and len(text) > 30: | |
| texts.append(text) | |
| full_text = "\n".join(texts) | |
| document = Document( | |
| page_content=full_text, | |
| metadata={"source": url} | |
| ) | |
| return [document] | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Error scraping website: {str(e)}") | |
| def generate_response(message: str, vector_db, api_key: str, model: str): | |
| """Generate chatbot response using RAG""" | |
| try: | |
| # Retrieve relevant chunks | |
| result = vector_db.similarity_search(message, k=3) | |
| context = [] | |
| for i in result: | |
| context.append(f"Chunk: {i.page_content}") | |
| # Create Groq client | |
| client = Groq(api_key=api_key) | |
| prompt = """ | |
| You are a smart chatbot. You need to respond to user questions only by referring to the data present within the below knowledge base. | |
| 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. | |
| """ | |
| finalprompt = f"{prompt}\n\nKnowledge Base: {context}" | |
| completion = client.chat.completions.create( | |
| model=model, | |
| messages=[ | |
| { | |
| "role": "system", | |
| "content": finalprompt | |
| }, | |
| { | |
| "role": "user", | |
| "content": message | |
| } | |
| ], | |
| temperature=0, | |
| max_completion_tokens=1024 | |
| ) | |
| return completion.choices[0].message.content | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Error generating response: {str(e)}") | |
| # API Endpoints | |
| async def root(): | |
| return { | |
| "message": "RAG Chatbot API", | |
| "version": "1.0.0", | |
| "endpoints": { | |
| "POST /session/create": "Create a new session", | |
| "POST /upload/pdf": "Upload and process PDF", | |
| "POST /scrape/web": "Scrape website content", | |
| "POST /chat": "Send a chat message", | |
| "GET /session/{session_id}": "Get session info", | |
| "DELETE /session/{session_id}": "Delete a session" | |
| } | |
| } | |
| async def create_session(): | |
| """Create a new chat session""" | |
| session_id = str(uuid.uuid4()) | |
| sessions[session_id] = { | |
| "vector_db": None, | |
| "chat_history": [], | |
| "rag_type": None | |
| } | |
| return {"session_id": session_id, "message": "Session created successfully"} | |
| async def upload_pdf( | |
| file: UploadFile = File(...), | |
| session_id: Optional[str] = Form(None) | |
| ): | |
| """Upload and process a PDF file""" | |
| # Create session if not provided | |
| if not session_id: | |
| session_id = str(uuid.uuid4()) | |
| sessions[session_id] = { | |
| "vector_db": None, | |
| "chat_history": [], | |
| "rag_type": None | |
| } | |
| if session_id not in sessions: | |
| raise HTTPException(status_code=404, detail="Session not found") | |
| # Validate file type | |
| if not file.filename.endswith('.pdf'): | |
| raise HTTPException(status_code=400, detail="Only PDF files are supported") | |
| # Save uploaded file temporarily | |
| with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file: | |
| content = await file.read() | |
| tmp_file.write(content) | |
| tmp_path = tmp_file.name | |
| try: | |
| # Load embeddings | |
| embeddings = load_embeddings() | |
| # Process PDF | |
| docs = process_pdf(tmp_path) | |
| # Create vector database | |
| vector_db, num_chunks = create_vector_db(docs, embeddings) | |
| # Store in session | |
| sessions[session_id]["vector_db"] = vector_db | |
| sessions[session_id]["rag_type"] = "PDF" | |
| sessions[session_id]["chat_history"] = [] | |
| return SessionResponse( | |
| session_id=session_id, | |
| message="PDF processed successfully", | |
| num_chunks=num_chunks, | |
| rag_type="PDF" | |
| ) | |
| finally: | |
| # Clean up temp file | |
| os.unlink(tmp_path) | |
| async def scrape_web(request: WebScrapingRequest): | |
| """Scrape website and create vector database""" | |
| # Create session if not provided | |
| session_id = request.session_id or str(uuid.uuid4()) | |
| if session_id not in sessions: | |
| sessions[session_id] = { | |
| "vector_db": None, | |
| "chat_history": [], | |
| "rag_type": None | |
| } | |
| # Load embeddings | |
| embeddings = load_embeddings() | |
| # Scrape website | |
| documents = scrape_website(str(request.url)) | |
| # Create vector database | |
| vector_db, num_chunks = create_vector_db(documents, embeddings) | |
| # Store in session | |
| sessions[session_id]["vector_db"] = vector_db | |
| sessions[session_id]["rag_type"] = "Web" | |
| sessions[session_id]["chat_history"] = [] | |
| return SessionResponse( | |
| session_id=session_id, | |
| message="Website scraped successfully", | |
| num_chunks=num_chunks, | |
| rag_type="Web" | |
| ) | |
| async def chat(request: ChatRequest): | |
| """Send a chat message and get a response""" | |
| if request.session_id not in sessions: | |
| raise HTTPException(status_code=404, detail="Session not found") | |
| session = sessions[request.session_id] | |
| if session["vector_db"] is None: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="No knowledge base loaded. Please upload a PDF or scrape a website first." | |
| ) | |
| # Generate response | |
| answer = generate_response( | |
| request.message, | |
| session["vector_db"], | |
| request.api_key, | |
| request.model | |
| ) | |
| # Store in chat history | |
| chat_entry = { | |
| "question": request.message, | |
| "answer": answer | |
| } | |
| session["chat_history"].append(chat_entry) | |
| return ChatResponse( | |
| session_id=request.session_id, | |
| question=request.message, | |
| answer=answer | |
| ) | |
| async def get_session(session_id: str): | |
| """Get session information""" | |
| if session_id not in sessions: | |
| raise HTTPException(status_code=404, detail="Session not found") | |
| session = sessions[session_id] | |
| return SessionInfo( | |
| session_id=session_id, | |
| rag_type=session["rag_type"], | |
| chat_history=session["chat_history"], | |
| has_vector_db=session["vector_db"] is not None | |
| ) | |
| async def delete_session(session_id: str): | |
| """Delete a session""" | |
| if session_id not in sessions: | |
| raise HTTPException(status_code=404, detail="Session not found") | |
| del sessions[session_id] | |
| return {"message": "Session deleted successfully"} | |
| async def list_sessions(): | |
| """List all active sessions""" | |
| session_list = [] | |
| for session_id, data in sessions.items(): | |
| session_list.append({ | |
| "session_id": session_id, | |
| "rag_type": data["rag_type"], | |
| "has_vector_db": data["vector_db"] is not None, | |
| "chat_count": len(data["chat_history"]) | |
| }) | |
| return {"sessions": session_list} | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=8000) |