File size: 2,002 Bytes
4a6d122 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | 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)
|