Spaces:
Sleeping
Sleeping
File size: 13,022 Bytes
98cf243 c6aa66a 35fbb15 c6aa66a 98cf243 c6aa66a 35fbb15 2cc4145 35fbb15 98cf243 35fbb15 c6aa66a 35fbb15 c6aa66a 35fbb15 98cf243 c6aa66a 35fbb15 c6aa66a 35fbb15 c6aa66a 35fbb15 c6aa66a 35fbb15 c6aa66a 35fbb15 c6aa66a 35fbb15 2cc4145 35fbb15 c6aa66a 35fbb15 c6aa66a 35fbb15 c6aa66a 35fbb15 c6aa66a 35fbb15 c6aa66a 35fbb15 c6aa66a 35fbb15 c6aa66a 98cf243 c6aa66a 35fbb15 98cf243 35fbb15 c6aa66a 35fbb15 c6aa66a 35fbb15 c6aa66a 35fbb15 c6aa66a 35fbb15 c6aa66a 98cf243 35fbb15 c6aa66a 3e085e1 c6aa66a 35fbb15 | 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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 | import asyncio
import json
import os
import shutil
import time
import traceback
from collections import defaultdict, deque
from pathlib import Path
from contextlib import asynccontextmanager
from fastapi import FastAPI, UploadFile, File, HTTPException, Depends, Header, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, StreamingResponse
from pydantic import BaseModel
from dotenv import load_dotenv
from starlette.concurrency import run_in_threadpool
from ingest import ingest_pdf, remove_pdf, load_vector_store, DOCUMENTS_PATH, IMAGES_PATH
from rag import build_engine
import db
load_dotenv(Path(__file__).parent.parent / ".env")
FRONTEND_PATH = Path(__file__).parent.parent / "frontend"
# Global RAG state loaded once at startup and refreshed after uploads
_engine = None
def refresh_rag():
global _engine
store = load_vector_store()
_engine = build_engine(store) if store is not None else None
@asynccontextmanager
async def lifespan(app: FastAPI):
refresh_rag()
yield
app = FastAPI(title="Docent AI β Policy Chatbot", lifespan=lifespan)
@app.exception_handler(Exception)
async def unhandled_exception(request: Request, exc: Exception):
"""Unhandled errors would return a bare 500 with no explanation; instead
log the traceback and tell the client what actually failed."""
traceback.print_exc()
return JSONResponse(
status_code=500,
content={"detail": f"Unexpected server error ({type(exc).__name__}: {exc}). Please try again."},
)
# Serve frontend static files, extracted images, and the original PDFs
# (PDFs are needed by the in-browser reference preview to jump to the cited page)
app.mount("/static", StaticFiles(directory=str(FRONTEND_PATH)), name="static")
app.mount("/images", StaticFiles(directory=str(IMAGES_PATH)), name="images")
app.mount("/docs", StaticFiles(directory=str(DOCUMENTS_PATH)), name="docs")
# ---------- Models ----------
class ChatRequest(BaseModel):
question: str
session_id: str | None = None
class RenameRequest(BaseModel):
title: str
class FeedbackRequest(BaseModel):
value: str | None = None # 'up', 'down', or null to clear
# ---------- Rate limiting (protects the free NVIDIA quota) ----------
RATE_LIMIT = int(os.environ.get("RATE_LIMIT_PER_10MIN", "30"))
_rate: dict[str, deque] = defaultdict(deque)
def _check_rate(user_id: str) -> bool:
now = time.time()
dq = _rate[user_id]
while dq and dq[0] < now - 600:
dq.popleft()
if len(dq) >= RATE_LIMIT:
return False
dq.append(now)
return True
# ---------- Auth dependency ----------
async def get_current_user(authorization: str | None = Header(default=None)):
if not authorization or not authorization.lower().startswith("bearer "):
raise HTTPException(status_code=401, detail="Not authenticated.")
token = authorization.split(" ", 1)[1].strip()
user = db.verify_token(token)
if user is None:
raise HTTPException(status_code=401, detail="Invalid or expired session.")
return user
async def get_admin_user(user=Depends(get_current_user)):
if not db.is_admin(user):
raise HTTPException(status_code=403, detail="Admin access required.")
return user
def _attach_image_urls(sources: list[dict]) -> list[dict]:
for src in sources:
src["image_urls"] = [f"/images/{fname}" for fname in src.get("images", [])]
return sources
# ---------- Routes ----------
# HTML must always revalidate β stale cached pages point at old JS/CSS
_NO_CACHE = {"Cache-Control": "no-cache"}
@app.get("/")
async def root(request: Request):
# Link-preview crawlers (WhatsApp/Discord) require ABSOLUTE og: URLs, so
# inject this server's own address into the meta tags.
scheme = request.headers.get("x-forwarded-proto", request.url.scheme)
base = f"{scheme}://{request.url.netloc}"
html = (FRONTEND_PATH / "index.html").read_text(encoding="utf-8")
return HTMLResponse(html.replace("__BASE_URL__", base), headers=_NO_CACHE)
@app.get("/favicon.ico")
async def favicon():
return FileResponse(str(FRONTEND_PATH / "favicon.ico"))
@app.get("/config")
async def config():
"""Public config the frontend needs to initialise Supabase auth."""
return {
"supabaseUrl": db.SUPABASE_URL,
"supabaseAnonKey": db.SUPABASE_ANON_KEY,
"configured": db.is_configured(),
}
@app.get("/me")
async def me(user=Depends(get_current_user)):
"""Who am I β lets the frontend show/hide admin-only UI."""
return {"email": user.email, "is_admin": db.is_admin(user)}
@app.post("/upload")
async def upload_documents(
files: list[UploadFile] = File(...),
user=Depends(get_admin_user),
):
"""Accept one or more PDF files, ingest them into the FAISS store."""
if not files:
raise HTTPException(status_code=400, detail="No files provided.")
results = []
for upload in files:
if not upload.filename.lower().endswith(".pdf"):
results.append({"file": upload.filename, "status": "skipped β not a PDF"})
continue
dest = DOCUMENTS_PATH / upload.filename
if dest.exists():
# Re-ingesting would add duplicate chunks to the FAISS index
results.append({"file": upload.filename, "status": "skipped β already ingested"})
continue
with open(dest, "wb") as f:
shutil.copyfileobj(upload.file, f)
try:
# Ingestion embeds every chunk via the NVIDIA API β run it off the
# event loop so chat stays responsive during uploads.
chunks = await run_in_threadpool(ingest_pdf, str(dest))
results.append({"file": upload.filename, "status": "ingested", "chunks": chunks})
except Exception as e:
dest.unlink(missing_ok=True) # don't leave a half-ingested file behind
results.append({"file": upload.filename, "status": f"error: {e}"})
refresh_rag()
return {"results": results}
@app.get("/documents")
async def list_documents(user=Depends(get_admin_user)):
"""List all PDF filenames stored in the documents folder."""
pdfs = sorted(
p.name for p in DOCUMENTS_PATH.iterdir() if p.suffix.lower() == ".pdf"
)
return {"documents": pdfs}
@app.delete("/documents/{filename}")
async def delete_document(filename: str, user=Depends(get_admin_user)):
"""Remove a PDF and all of its chunks from the index."""
if Path(filename).name != filename or not filename.lower().endswith(".pdf"):
raise HTTPException(status_code=400, detail="Invalid filename.")
if not (DOCUMENTS_PATH / filename).exists():
raise HTTPException(status_code=404, detail="Document not found.")
removed = await run_in_threadpool(remove_pdf, filename)
refresh_rag()
return {"file": filename, "chunks_removed": removed}
@app.get("/admin")
async def admin_dashboard():
"""Serves the admin analytics dashboard (data endpoints enforce the admin role)."""
return FileResponse(str(FRONTEND_PATH / "admin.html"), headers=_NO_CACHE)
@app.get("/analytics")
async def get_analytics(user=Depends(get_admin_user)):
"""Usage statistics: questions, citations per document, unanswered questions."""
data = await run_in_threadpool(db.analytics)
data["total_documents"] = sum(
1 for p in DOCUMENTS_PATH.iterdir() if p.suffix.lower() == ".pdf"
)
data["total_chunks"] = (
len(getattr(_engine.vector_store.docstore, "_dict", {})) if _engine else 0
)
return data
@app.post("/analytics/clear-unanswered")
async def clear_unanswered(user=Depends(get_admin_user)):
"""Dismiss the current unanswered questions from the dashboard."""
db.clear_unanswered()
return {"ok": True}
@app.post("/messages/{message_id}/feedback")
async def message_feedback(message_id: str, req: FeedbackRequest, user=Depends(get_current_user)):
if req.value not in (None, "up", "down"):
raise HTTPException(status_code=400, detail="Feedback must be 'up', 'down' or null.")
if not db.set_feedback(message_id, user.id, req.value):
raise HTTPException(status_code=404, detail="Message not found.")
return {"ok": True}
# ---------- Sessions / history ----------
@app.get("/sessions")
async def get_sessions(user=Depends(get_current_user)):
return {"sessions": db.list_sessions(user.id)}
@app.post("/sessions")
async def new_session(user=Depends(get_current_user)):
sess = db.create_session(user.id, "New chat")
return sess
@app.delete("/sessions")
async def remove_all_sessions(user=Depends(get_current_user)):
"""Delete every conversation belonging to the current user."""
db.delete_all_sessions(user.id)
return {"ok": True}
@app.get("/sessions/{session_id}/messages")
async def get_session_messages(session_id: str, user=Depends(get_current_user)):
if db.get_session(session_id, user.id) is None:
raise HTTPException(status_code=404, detail="Conversation not found.")
messages = db.list_messages(session_id)
for m in messages:
if m.get("sources"):
_attach_image_urls(m["sources"])
return {"messages": messages}
@app.patch("/sessions/{session_id}")
async def rename_session(session_id: str, req: RenameRequest, user=Depends(get_current_user)):
if db.get_session(session_id, user.id) is None:
raise HTTPException(status_code=404, detail="Conversation not found.")
title = req.title.strip()
if not title:
raise HTTPException(status_code=400, detail="Title cannot be empty.")
db.rename_session(session_id, user.id, title)
return {"ok": True}
@app.delete("/sessions/{session_id}")
async def remove_session(session_id: str, user=Depends(get_current_user)):
db.delete_session(session_id, user.id)
return {"ok": True}
@app.post("/chat")
async def chat(req: ChatRequest, user=Depends(get_current_user)):
"""Answer a question, streaming tokens as server-sent events:
a `meta` event (session + sources) first, then `delta` events, then `done`."""
if not req.question.strip():
raise HTTPException(status_code=400, detail="Question cannot be empty.")
if not _check_rate(user.id):
raise HTTPException(
status_code=429,
detail="You're sending messages too quickly. Please wait a few minutes.",
)
if _engine is None:
raise HTTPException(
status_code=503,
detail="No documents have been ingested yet. Please upload policy PDFs first.",
)
# Resolve or create the conversation
if req.session_id:
session = db.get_session(req.session_id, user.id)
if session is None:
raise HTTPException(status_code=404, detail="Conversation not found.")
else:
title = req.question.strip()[:60]
session = db.create_session(user.id, title)
session_id = session["id"]
# Load prior turns BEFORE storing the new question, to use as memory
history = db.list_messages(session_id)
db.add_message(session_id, "user", req.question)
try:
sources, token_gen = _engine.answer_stream(req.question, history)
except Exception:
# Free NVIDIA endpoints hiccup occasionally β one retry clears most of it
await asyncio.sleep(1.0)
try:
sources, token_gen = _engine.answer_stream(req.question, history)
except Exception as e:
raise HTTPException(status_code=500, detail=f"LLM error: {e}")
_attach_image_urls(sources)
def sse():
def event(obj: dict) -> str:
return f"data: {json.dumps(obj)}\n\n"
# 2KB SSE comment: harmless to clients, but overflows the sniff buffer
# of AV/proxy software that would otherwise buffer the whole response.
yield ":" + " " * 2048 + "\n\n"
yield event({
"type": "meta",
"session_id": session_id,
"title": session["title"],
"sources": sources,
})
parts = []
try:
for token in token_gen:
if token:
parts.append(token)
yield event({"type": "delta", "text": token})
except Exception as e:
yield event({"type": "error", "detail": f"LLM error: {e}"})
answer = "".join(parts)
saved = None
if answer.strip():
# A refusal cites nothing β don't attach sources/images to it
msg_sources = [] if answer.strip().startswith(db.NO_ANSWER_PREFIX) else sources
saved = db.add_message(session_id, "assistant", answer, msg_sources)
db.touch_session(session_id)
yield event({"type": "done", "message_id": (saved or {}).get("id")})
return StreamingResponse(
sse(),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
|