from fastapi import FastAPI, UploadFile, File, HTTPException from fastapi.middleware.cors import CORSMiddleware from typing import List from pydantic import BaseModel from src.config import conf from src.ingestion import DocumentProcessor from src.rag_engine import engine app = FastAPI(title=conf.APP_NAME, version=conf.VERSION) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) class QueryRequest(BaseModel): question: str @app.get("/") def health_check(): return {"status": "operational", "system": conf.APP_NAME} @app.post("/ingest") async def ingest_documents(files: List[UploadFile] = File(...)): """Uploads PDFs, extracts text, and rebuilds the vector index.""" if not files: raise HTTPException(400, "No files uploaded") try: # 1. Extraction raw_text = DocumentProcessor.extract_text(files) if not raw_text.strip(): raise HTTPException(400, "No text extracted from documents") # 2. Chunking chunks = DocumentProcessor.chunk_text(raw_text) # 3. Vectorization engine.ingest(chunks) return {"status": "success", "chunks_processed": len(chunks)} except Exception as e: raise HTTPException(500, f"Ingestion failed: {str(e)}") @app.post("/ask") async def ask_question(req: QueryRequest): """Queries the RAG engine.""" try: answer = engine.query(req.question) return {"question": req.question, "answer": answer} except ValueError: raise HTTPException(400, "Please upload documents first via /ingest") except Exception as e: raise HTTPException(500, f"Inference failed: {str(e)}")