Spaces:
Running
Running
| import os | |
| from pathlib import Path | |
| from fastapi import FastAPI, File, HTTPException, UploadFile | |
| from pydantic import BaseModel | |
| from rag import answer_question, index_pdf | |
| BASE_DIR = Path(__file__).resolve().parent.parent | |
| DATA_DIR = Path(os.getenv("DATA_DIR", BASE_DIR / "data")) | |
| UPLOAD_DIR = DATA_DIR / "uploads" | |
| UPLOAD_DIR.mkdir(parents=True, exist_ok=True) | |
| app = FastAPI(title="PDF RAG Chatbot") | |
| class AskRequest(BaseModel): | |
| question: str | |
| def health(): | |
| return {"status": "ok"} | |
| async def upload_pdf(file: UploadFile = File(...)): | |
| if not file.filename.lower().endswith(".pdf"): | |
| raise HTTPException(status_code=400, detail="PDF νμΌλ§ μ λ‘λν μ μμ΅λλ€.") | |
| save_path = UPLOAD_DIR / file.filename | |
| content = await file.read() | |
| save_path.write_bytes(content) | |
| try: | |
| result = index_pdf(save_path) | |
| except RuntimeError as error: | |
| raise HTTPException(status_code=500, detail=str(error)) from error | |
| return { | |
| "filename": file.filename, | |
| "chunks": result["chunks"], | |
| "message": "PDF μ λ‘λ λ° μΈλ±μ±μ΄ μλ£λμμ΅λλ€.", | |
| } | |
| def ask(request: AskRequest): | |
| if not request.question.strip(): | |
| raise HTTPException(status_code=400, detail="μ§λ¬Έμ μ λ ₯ν΄ μ£ΌμΈμ.") | |
| try: | |
| return answer_question(request.question) | |
| except RuntimeError as error: | |
| raise HTTPException(status_code=500, detail=str(error)) from error | |