Download main.py from Aner-1324/PDF_RAG: direct link, hf CLI and curl.
- Browser
- Download file 2 kB
-
https://huggingface.co/spaces/Aner-1324/PDF_RAG/resolve/main/main.py
- Command line
-
hf download hf://spaces/Aner-1324/PDF_RAG/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Aner-1324/PDF_RAG/resolve/main/main.py
2 kB
| 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) | |
| async def root(): | |
| return {"message": "PDF RAG API is running."} | |
| 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)) | |
| 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) | |