MAbdullah03/smart-med-notes
0
1from fastapi import FastAPI, HTTPException2from pydantic import BaseModel3import uvicorn4import logging5import os6# Import your custom modules7from models.phi3 import retrieve_faiss_docs, generate_response8from models.summarizer import summarize_context9 10 11# Configure logging12logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")13 14 15# Check required files before starting the app16if not os.path.exists("processed_data/combined_faiss_index.faiss"):17 logging.error("FAISS index not found! Please generate it before deployment.")18 raise FileNotFoundError("FAISS index is missing at processed_data/combined_faiss_index.faiss")19 20 21# Initialize FastAPI22app = FastAPI()23 24# Input schema for POST request25class QueryRequest(BaseModel):26 query: str27 28@app.get("/")29async def home():30 return {"message": "✅ FastAPI backend is running successfully!"}31 32@app.post("/rag")33async def rag_pipeline(request: QueryRequest):34 user_query = request.query.strip()35 36 if not user_query:37 logging.warning("❗ Empty query received.")38 raise HTTPException(status_code=400, detail="Query cannot be empty.")39 40 logging.info(f"📥 Query received: {user_query}")41 42 # Step 1: Retrieve top documents43 retrieved_docs = retrieve_faiss_docs(user_query)44 logging.info(f"📚 Retrieved {len(retrieved_docs)} documents.")45 46 if not retrieved_docs:47 logging.warning("⚠️ No relevant documents found.")48 return {"query": user_query, "response": "Sorry, no relevant medical information found."}49 50 # Step 2: Summarize context using T5-small51 combined_context = " ".join(retrieved_docs)52 summarized_context = summarize_context(combined_context)53 logging.info("📝 Context summarized.")54 55 # Step 3: Generate response from LLM with full output56 final_response = generate_response(user_query)57 logging.info("🤖 Response generated by LLM.")58 59 return {"query": user_query, "response": final_response}60 61# Run with Uvicorn62def start():63 uvicorn.run(app, host="0.0.0.0", port=7860)64 65if __name__ == "__main__":66 start()67 