PadmasaliGovardhan
final update
e4cf488
from dotenv import load_dotenv
load_dotenv()
from fastapi.responses import HTMLResponse
from fastapi import FastAPI, UploadFile, Form, File
from fastapi.middleware.cors import CORSMiddleware
import fitz
import os
# keep package-relative import if this is inside app/
from .rag_app import RAGApp
app = FastAPI(title="Personal Assistant")
# Initialize RagApp safely
try:
rag = RAGApp()
except Exception as e:
rag = None
print("Initialization error in RagApp:", e)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Use a writable, ephemeral path suitable for Spaces
UPLOAD_DIR = "/tmp/notes"
os.makedirs(UPLOAD_DIR, exist_ok=True)
def extract_text_from_pdf(pdf_path):
text = ""
with fitz.open(pdf_path) as doc:
for page in doc:
text += page.get_text()
return text\
@app.get("/", response_class=HTMLResponse)
def home():
return """
<html>
<head>
<title>AI NoteBook Assistant (RAG)</title>
<style>
body {
background-color: #0f0f0f;
color: #e0e0e0;
font-family: 'Inter', sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
h1 {
color: #facc15;
margin-bottom: 10px;
}
a {
color: #22d3ee;
text-decoration: none;
font-weight: bold;
background: rgba(255,255,255,0.1);
padding: 10px 20px;
border-radius: 10px;
transition: all 0.3s ease;
}
a:hover {
background: #22d3ee;
color: #000;
}
</style>
</head>
<body>
<h1>πŸš€ AI NoteBook Assistant Backend is Running!</h1>
<p>Access the frontend from here:</p>
<a href="https://ai-notebook-rag.netlify.app" target="_blank">
Open AI Notes Assistant App
</a>
<p style="margin-top:20px; opacity:0.7;">Made by Govardhan πŸ’›</p>
</body>
</html>
"""
@app.post("/upload_pdf/")
async def upload_pdf(file: UploadFile = File(...)):
filename = os.path.basename(file.filename)
path = os.path.join(UPLOAD_DIR, filename)
try:
with open(path, "wb") as f:
f.write(await file.read())
if rag is None:
return {"status": "error", "detail": "Server initialization failed. RagApp not ready."}
text = extract_text_from_pdf(path)
if not text.strip():
return {"status": "error", "detail": "Uploaded PDF contains no extractable text."}
chunks = rag.add_notes(text)
return {"status": "success", "message": f"{filename} is uploaded sucessfully...!"}
except Exception as e:
import traceback
return {
"status": "error",
"detail": str(e),
"traceback": traceback.format_exc()
}
@app.post("/ask/")
async def ask_question(query: str = Form(...)):
if rag is None:
return {"status": "error", "detail": "Server initialization failed. RagApp not ready."}
answer = rag.ask(query)
return {"question": query, "answer": answer}