from fastapi import FastAPI, UploadFile, File, HTTPException from fastapi.middleware.cors import CORSMiddleware from rag_logic import rag_engine import os import shutil app = FastAPI(title="Open-Source PDF RAG API") # Enable CORS for Next.js frontend app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) UPLOAD_DIR = "uploads" os.makedirs(UPLOAD_DIR, exist_ok=True) @app.get("/") async def root(): return {"message": "PDF RAG API is running."} @app.post("/upload") async def upload_pdf(file: UploadFile = File(...)): print(f"DEBUG: Received upload request for file: {file.filename}") if not file.filename.lower().endswith(".pdf"): print("DEBUG: Rejected non-PDF file") raise HTTPException(status_code=400, detail="Only PDF files are allowed.") file_path = os.path.join(UPLOAD_DIR, file.filename) try: print(f"DEBUG: Saving file to {file_path}") with open(file_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer) print("DEBUG: File saved. Starting PDF processing...") num_chunks = rag_engine.process_pdf(file_path) print(f"DEBUG: PDF processed successfully. {num_chunks} chunks.") return {"message": f"PDF processed successfully. {num_chunks} chunks created."} except Exception as e: print(f"DEBUG: Error during upload/processing: {str(e)}") if os.path.exists(file_path): os.remove(file_path) raise HTTPException(status_code=500, detail=str(e)) @app.post("/ask") async def ask_question(query: str): print(f"DEBUG: Processing question: {query}") try: response = rag_engine.ask(query) return {"response": response} except Exception as e: print(f"DEBUG: Error in /ask route: {str(e)}") raise HTTPException(status_code=500, detail=str(e)) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)