Spaces:
Sleeping
Sleeping
Download backend/main.py from Abdullah0327/Docent-AI-ChatBot: direct link, hf CLI and curl.
- Browser
- Download file 13 kB
-
https://huggingface.co/spaces/Abdullah0327/Docent-AI-ChatBot/resolve/main/backend/main.py
- Command line
-
hf download hf://spaces/Abdullah0327/Docent-AI-ChatBot/backend/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Abdullah0327/Docent-AI-ChatBot/resolve/main/backend/main.py
13 kB
| 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 | |
| async def lifespan(app: FastAPI): | |
| refresh_rag() | |
| yield | |
| app = FastAPI(title="Docent AI β Policy Chatbot", lifespan=lifespan) | |
| 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"} | |
| 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) | |
| async def favicon(): | |
| return FileResponse(str(FRONTEND_PATH / "favicon.ico")) | |
| 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(), | |
| } | |
| 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)} | |
| 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} | |
| 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} | |
| 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} | |
| 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) | |
| 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 | |
| async def clear_unanswered(user=Depends(get_admin_user)): | |
| """Dismiss the current unanswered questions from the dashboard.""" | |
| db.clear_unanswered() | |
| return {"ok": True} | |
| 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 ---------- | |
| async def get_sessions(user=Depends(get_current_user)): | |
| return {"sessions": db.list_sessions(user.id)} | |
| async def new_session(user=Depends(get_current_user)): | |
| sess = db.create_session(user.id, "New chat") | |
| return sess | |
| 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} | |
| 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} | |
| 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} | |
| async def remove_session(session_id: str, user=Depends(get_current_user)): | |
| db.delete_session(session_id, user.id) | |
| return {"ok": True} | |
| 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"}, | |
| ) | |