Spaces:
Sleeping
Sleeping
Commit Β·
c6aa66a
1
Parent(s): fd4ea61
new ai model and ui changes with new admin functionality implemented
Browse filesFiles changed (15)
- README.md+34-19
- backend/db.py+129-2
- backend/ingest.py+63
- backend/main.py+158-21
- backend/rag.py+281-27
- eval_questions.jsonAdded+62
- evaluate.pyAdded+82
- frontend/admin.htmlAdded+409
- frontend/index.html+56-7
- frontend/script.js+749-70
- frontend/style.css+537-14
- requirements.txt+1
- supabase_schema.sql+3
- vector_db/index.faiss+1-1
- vector_db/index.pkl+2-2
14 unmodified lines15161718192021222324252633 unmodified lines606162636465666761 unmodified lines1291301311321331341351361371381391401416 unmodified lines1481491501511521531541551561571581591601611621631641656 unmodified lines17217317417517617717814 unmodified lines## Features- **User authentication** (Supabase email/password) β each user has their own private chats- **Persistent chat history** β conversations are stored in Supabase and reload on login- **Conversational memory** β follow-up questions ("what about for managers?") are understood using prior turns via a history-aware retriever- Upload one or many PDF documents; they are indexed and **persisted** in a FAISS vector store- Answers come **only from the documents** β the LLM is instructed never to hallucinate or use outside knowledge- Every answer shows **source file + page number** references (persisted with history)- Adding more PDFs at any time merges them into the existing index with no data loss## Project Structure33 unmodified linesSUPABASE_URL=https://<project-ref>.supabase.coSUPABASE_ANON_KEY=eyJ...SUPABASE_SERVICE_ROLE_KEY=eyJ...```### 3. Set up Supabase (one time)1. Open your project β **SQL Editor** β **New query**.61 unmodified lines|--------|------|-------------|| `GET` | `/` | Serves the chat UI || `GET` | `/config` | Public Supabase URL + anon key for the frontend || `POST` | `/upload` | Upload one or more PDF files (auth) || `GET` | `/documents` | List all ingested document filenames (auth) || `GET` | `/sessions` | List the user's conversations (auth) || `POST` | `/sessions` | Create a new conversation (auth) || `GET` | `/sessions/{id}/messages` | Load a conversation's messages (auth) || `DELETE` | `/sessions/{id}` | Delete a conversation (auth) || `POST` | `/chat` | Send a question, get an answer + sources (auth) |### `/chat` request body6 unmodified linesIf `session_id` is omitted, a new conversation is created automatically.### `/chat` response```json{"answer": "According to the HR Policy document, employees are entitled to ...","sources": [{ "file": "hr-policy.pdf", "page": 4, "image_urls": [] }],"session_id": "β¦","title": "What is the leave policy?"}```## How conversational memory works6 unmodified lines| Component | Library ||-----------|---------|| LLM | `langchain-nvidia-ai-endpoints` β `ChatNVIDIA` (`meta/llama-3.3-70b-instruct`) || Embeddings | `NVIDIAEmbeddings` (`nvidia/nv-embedqa-e5-v5`) || Vector store | `faiss-cpu` (persisted to disk) || Auth & history | Supabase (Postgres + Auth) |14 unmodified lines15161718192021222324252627282933 unmodified lines636465666768697071727374757661 unmodified lines1381391401411421431441451461471481491501511521536 unmodified lines1601611621631641651661671681691701711721731741751761771781791806 unmodified lines18718818919019119219314 unmodified lines## Features- **User authentication** (Supabase email/password) β each user has their own private chats- **Admin role** β only emails listed in `ADMIN_EMAILS` can upload/manage documents; everyone else can only chat (enforced server-side)- **Persistent chat history** β conversations are stored in Supabase and reload on login; rename or delete them from the sidebar- **Conversational memory** β follow-up questions ("what about for managers?") are understood using prior turns via a history-aware retriever- **Streaming answers** β tokens appear as they are generated (server-sent events), with a stop button to cancel- **Clickable references with PDF preview** β every answer cites file + page; clicking a citation opens the PDF in an in-page modal at that exact page with the retrieved passage highlighted (PDF.js)- Answers come **only from the documents** β strict context-only prompt, temperature 0, and low-relevance chunks are filtered out before reaching the LLM- **Markdown-rendered answers** (sanitised with DOMPurify)- Upload one or many PDF documents; they are indexed and **persisted** in a FAISS vector store; duplicates are skipped and ingestion runs off the event loop so chat stays responsive- Automatic **fallback to a lighter model** when NVIDIA's free 70B endpoint is congested (504s)## Project Structure33 unmodified linesSUPABASE_URL=https://<project-ref>.supabase.coSUPABASE_ANON_KEY=eyJ...SUPABASE_SERVICE_ROLE_KEY=eyJ...ADMIN_EMAILS=admin@example.com # comma-separated; these users can upload PDFs```Optional overrides: `CHAT_MODEL` (default `nvidia/llama-3.3-nemotron-super-49b-v1.5`),`CONDENSE_MODEL` (default `meta/llama-3.1-8b-instruct`, also used as thefallback answer model), and `FIRST_TOKEN_TIMEOUT` (default 25s β how long towait for the primary model before answering with the fallback).### 3. Set up Supabase (one time)1. Open your project β **SQL Editor** β **New query**.61 unmodified lines|--------|------|-------------|| `GET` | `/` | Serves the chat UI || `GET` | `/config` | Public Supabase URL + anon key for the frontend || `GET` | `/me` | Current user's email + admin flag (auth) || `GET` | `/docs/{filename}` | Serves an original PDF (used by the reference preview) || `POST` | `/upload` | Upload one or more PDF files (**admin**) || `GET` | `/documents` | List all ingested document filenames (**admin**) || `GET` | `/sessions` | List the user's conversations (auth) || `POST` | `/sessions` | Create a new conversation (auth) || `GET` | `/sessions/{id}/messages` | Load a conversation's messages (auth) || `PATCH` | `/sessions/{id}` | Rename a conversation (auth) || `DELETE` | `/sessions/{id}` | Delete a conversation (auth) || `POST` | `/chat` | Send a question, stream the answer + sources (auth) |### `/chat` request body6 unmodified linesIf `session_id` is omitted, a new conversation is created automatically.### `/chat` response (server-sent event stream)```data: {"type": "meta", "session_id": "β¦", "title": "β¦", "sources": [{"file": "hr-policy.pdf", "page": 4, "snippets": ["β¦retrieved textβ¦"], "image_urls": []}]}data: {"type": "delta", "text": "According"}data: {"type": "delta", "text": " to the"}...data: {"type": "done"}````meta` arrives first (session + citations), then `delta` tokens as the modelgenerates, and finally `done`. A `{"type": "error"}` event is sent if the LLMfails mid-stream. The full answer is persisted to Supabase when the stream ends.## How conversational memory works6 unmodified lines| Component | Library ||-----------|---------|| LLM | `langchain-nvidia-ai-endpoints` β `ChatNVIDIA` (`nvidia/llama-3.3-nemotron-super-49b-v1.5`) || Embeddings | `NVIDIAEmbeddings` (`nvidia/nv-embedqa-e5-v5`) || Vector store | `faiss-cpu` (persisted to disk) || Auth & history | Supabase (Postgres + Auth) |
5 unmodified lines678910116 unmodified lines18192021222320 unmodified lines444546474849505152535455565766 unmodified lines1241251261271281291301311325 unmodified linesauthenticated user's id β never trust a client-supplied user id."""import osfrom pathlib import Pathfrom datetime import datetime, timezone6 unmodified linesSUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY", "")SERVICE_ROLE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY", "")_admin: Client | None = None20 unmodified lines# ββ Auth ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef verify_token(token: str):"""Validate a Supabase access token and return the user, or None."""try:res = admin().auth.get_user(token)return res.user if res else Noneexcept Exception:return None# ββ Sessions ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ66 unmodified linesres = (admin().table("messages").select("role, content, sources, created_at").eq("session_id", session_id).order("created_at").execute())return res.data or []5 unmodified lines67891011126 unmodified lines1920212223242526272829303120 unmodified lines52535455565758596061626364656667686970717273747576777879808182838485868788899066 unmodified lines1571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582595 unmodified linesauthenticated user's id β never trust a client-supplied user id."""import osimport timefrom pathlib import Pathfrom datetime import datetime, timezone6 unmodified linesSUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY", "")SERVICE_ROLE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY", "")# Comma-separated list of emails allowed to upload/manage documents.ADMIN_EMAILS = {e.strip().lower()for e in os.environ.get("ADMIN_EMAILS", "").split(",")if e.strip()}_admin: Client | None = None20 unmodified lines# ββ Auth ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Verifying a token is a network round-trip to Supabase; caching it briefly# shaves that latency off every request. Trade-off: a revoked token stays# usable for up to TOKEN_CACHE_TTL seconds.TOKEN_CACHE_TTL = 300_token_cache: dict[str, tuple[float, object]] = {}def verify_token(token: str):"""Validate a Supabase access token and return the user, or None."""now = time.monotonic()hit = _token_cache.get(token)if hit and hit[0] > now:return hit[1]try:res = admin().auth.get_user(token)user = res.user if res else Noneexcept Exception:return Noneif user is not None:if len(_token_cache) > 500:for k in [k for k, v in _token_cache.items() if v[0] <= now]:del _token_cache[k]_token_cache[token] = (now + TOKEN_CACHE_TTL, user)return userdef is_admin(user) -> bool:"""A user is an admin if their email is listed in ADMIN_EMAILS (.env)."""email = (getattr(user, "email", "") or "").lower()return bool(email) and email in ADMIN_EMAILS# ββ Sessions ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ66 unmodified linesres = (admin().table("messages").select("id, role, content, sources, feedback, created_at").eq("session_id", session_id).order("created_at").execute())return res.data or []def set_feedback(message_id: str, user_id: str, value: str | None) -> bool:"""Record π/π on a message. Verifies the message belongs to the user."""res = (admin().table("messages").select("session_id").eq("id", message_id).limit(1).execute())if not res.data:return Falseif get_session(res.data[0]["session_id"], user_id) is None:return Falseadmin().table("messages").update({"feedback": value}).eq("id", message_id).execute()return True# ββ Analytics (admin) βββββββββββββββββββββββββββββββββββββββββββββββββββββββββNO_ANSWER_PREFIX = "I don't have information"def analytics() -> dict:"""Aggregate usage statistics across all users."""sess = (admin().table("chat_sessions").select("id", count="exact").limit(1).execute())msgs = (admin().table("messages").select("role, content, sources, feedback, session_id, created_at").order("created_at").limit(5000).execute()).data or []total_questions = sum(1 for m in msgs if m.get("role") == "user")answers = [m for m in msgs if m.get("role") == "assistant"]fb_up = sum(1 for m in answers if m.get("feedback") == "up")fb_down = sum(1 for m in answers if m.get("feedback") == "down")# Which documents get cited, and which questions the bot could not answercited: dict[str, int] = {}last_user_question: dict[str, str] = {}unanswered: list[str] = []for m in msgs:if m.get("role") == "user":last_user_question[m.get("session_id")] = m.get("content", "")continueif (m.get("content") or "").startswith(NO_ANSWER_PREFIX):q = last_user_question.get(m.get("session_id"))if q:unanswered.append(q)for s in (m.get("sources") or []):f = s.get("file")if f:cited[f] = cited.get(f, 0) + 1top_documents = sorted(cited.items(), key=lambda x: -x[1])[:10]# Questions per day for the last 14 days (UTC)from datetime import timedelta, dateper_day: dict[str, int] = {}for m in msgs:if m.get("role") == "user":day = (m.get("created_at") or "")[:10]if day:per_day[day] = per_day.get(day, 0) + 1today = datetime.now(timezone.utc).date()daily = [{"date": (today - timedelta(days=i)).isoformat(),"count": per_day.get((today - timedelta(days=i)).isoformat(), 0)}for i in range(13, -1, -1)]return {"total_conversations": sess.count or 0,"total_questions": total_questions,"total_answers": len(answers),"feedback": {"up": fb_up, "down": fb_down},"unanswered_count": len(unanswered),"recent_unanswered": unanswered[-10:][::-1],"top_documents": [{"file": f, "citations": c} for f, c in top_documents],"daily_questions": daily,}
1234571 unmodified lines7778798081828384858639 unmodified lines126127128129130131import osimport jsonfrom pathlib import Pathfrom dotenv import load_dotenvfrom langchain_community.document_loaders import PyPDFLoader71 unmodified lines# ββ Text ingestion ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef load_and_split_pdf(pdf_path: str, page_images: dict[int, list[str]]) -> list:loader = PyPDFLoader(pdf_path)pages = loader.load()splitter = RecursiveCharacterTextSplitter(chunk_size=CHUNK_SIZE,chunk_overlap=CHUNK_OVERLAP,39 unmodified linesreturn len(chunks)def load_vector_store() -> FAISS | None:"""Load the persisted FAISS index. Returns None if no index exists yet."""index_file = VECTOR_DB_PATH / "index.faiss"12345671 unmodified lines7879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412539 unmodified lines165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194import osimport jsonimport refrom pathlib import Pathfrom dotenv import load_dotenvfrom langchain_community.document_loaders import PyPDFLoader71 unmodified lines# ββ Text ingestion ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ_COMMON_WORDS = frozenset("the of and to in a is for be or by on with as at an are shall will ""not this that from any university policy student students".split())def _english_ratio(text: str) -> float:words = re.findall(r"[a-zA-Z]+", text.lower())if not words:return 1.0 # nothing to judge β leave the page alonereturn sum(w in _COMMON_WORDS for w in words) / len(words)def _repair_shifted_text(text: str) -> str:"""Some PDFs embed fonts with a custom encoding that stores everycharacter shifted by a constant (and no ToUnicode map), so extractorsreturn gibberish like '3/$*,$5,60' for 'PLAGIARISM'. If a page doesn'tlook like English, try constant shifts and keep the best-scoring one."""if _english_ratio(text) > 0.08:return textbest, best_ratio = text, _english_ratio(text)for shift in range(1, 33):decoded = "".join(chr(o + shift) if 0x20 <= (o := ord(c)) + shift <= 0x7E else cfor c in text)ratio = _english_ratio(decoded)if ratio > best_ratio:best, best_ratio = decoded, ratio# Only accept a repair that clearly turned into Englishreturn best if best_ratio > 0.12 else textdef load_and_split_pdf(pdf_path: str, page_images: dict[int, list[str]]) -> list:loader = PyPDFLoader(pdf_path)pages = loader.load()for page in pages:page.page_content = _repair_shifted_text(page.page_content)splitter = RecursiveCharacterTextSplitter(chunk_size=CHUNK_SIZE,chunk_overlap=CHUNK_OVERLAP,39 unmodified linesreturn len(chunks)def remove_pdf(filename: str) -> int:"""Remove a document: delete its chunks from the FAISS index (by docstoreid β no re-embedding needed), the PDF file, and its extracted images.Returns the number of chunks removed."""removed = 0store = load_vector_store()if store is not None:ids = [doc_idfor doc_id, doc in getattr(store.docstore, "_dict", {}).items()if doc.metadata.get("source") == filename]if ids:store.delete(ids)store.save_local(str(VECTOR_DB_PATH))removed = len(ids)(DOCUMENTS_PATH / filename).unlink(missing_ok=True)stem = Path(filename).stemfor img in IMAGES_PATH.glob(f"{stem}_p*_i*.*"):img.unlink(missing_ok=True)return removeddef load_vector_store() -> FAISS | None:"""Load the persisted FAISS index. Returns None if no index exists yet."""index_file = VECTOR_DB_PATH / "index.faiss"
123456789101112131419 unmodified lines3435363738394041423 unmodified lines464748495051525354555657586 unmodified lines6566676869702 unmodified lines7374757677787980816 unmodified lines888990919293949596976 unmodified lines1041051061071081091101111121131141151161 unmodified line1181191201211221231241 unmodified line12612712812913013118 unmodified lines15015115215315415515615715815916016116216316416516617 unmodified lines184185186187188189190191192193194195196197198199200import shutilfrom pathlib import Pathfrom contextlib import asynccontextmanagerfrom fastapi import FastAPI, UploadFile, File, HTTPException, Depends, Headerfrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import FileResponsefrom pydantic import BaseModelfrom dotenv import load_dotenvfrom ingest import ingest_pdf, load_vector_store, DOCUMENTS_PATH, IMAGES_PATHfrom rag import build_engineimport db19 unmodified linesapp = FastAPI(title="Docent AI β Policy Chatbot", lifespan=lifespan)# Serve frontend static files and extracted imagesapp.mount("/static", StaticFiles(directory=str(FRONTEND_PATH)), name="static")app.mount("/images", StaticFiles(directory=str(IMAGES_PATH)), name="images")# ---------- Models ----------3 unmodified linessession_id: str | None = Noneclass ChatResponse(BaseModel):answer: strsources: list[dict]session_id: strtitle: str# ---------- Auth dependency ----------async def get_current_user(authorization: str | None = Header(default=None)):6 unmodified linesreturn userdef _attach_image_urls(sources: list[dict]) -> list[dict]:for src in sources:src["image_urls"] = [f"/images/{fname}" for fname in src.get("images", [])]2 unmodified lines# ---------- Routes ----------@app.get("/")async def root():return FileResponse(str(FRONTEND_PATH / "index.html"))@app.get("/config")6 unmodified lines}@app.post("/upload")async def upload_documents(files: list[UploadFile] = File(...),user=Depends(get_current_user),):"""Accept one or more PDF files, ingest them into the FAISS store."""if not files:6 unmodified linescontinuedest = DOCUMENTS_PATH / upload.filenamewith open(dest, "wb") as f:shutil.copyfileobj(upload.file, f)try:chunks = ingest_pdf(str(dest))results.append({"file": upload.filename, "status": "ingested", "chunks": chunks})except Exception as e:results.append({"file": upload.filename, "status": f"error: {e}"})refresh_rag()1 unmodified line@app.get("/documents")async def list_documents(user=Depends(get_current_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"1 unmodified linereturn {"documents": pdfs}# ---------- Sessions / history ----------@app.get("/sessions")18 unmodified linesreturn {"messages": messages}@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", response_model=ChatResponse)async def chat(req: ChatRequest, user=Depends(get_current_user)):if not req.question.strip():raise HTTPException(status_code=400, detail="Question cannot be empty.")if _engine is None:raise HTTPException(status_code=503,17 unmodified linesdb.add_message(session_id, "user", req.question)try:answer, sources = _engine.answer(req.question, history)except Exception as e:raise HTTPException(status_code=500, detail=f"LLM error: {e}")_attach_image_urls(sources)db.add_message(session_id, "assistant", answer, sources)db.touch_session(session_id)return ChatResponse(answer=answer,sources=sources,session_id=session_id,title=session["title"],)1234567891011121314151617181919 unmodified lines39404142434445464748493 unmodified lines535455565758596061626364656667686970717273747576777879808182836 unmodified lines909192939495969798991001012 unmodified lines1041051061071081091101111121131141151166 unmodified lines1231241251261271281291301311321331341351361371386 unmodified lines1451461471481491501511521531541551561571581591601611621631641651 unmodified line1671681691701711721731 unmodified line17517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022118 unmodified lines24024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427517 unmodified lines293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337import jsonimport osimport shutilimport timefrom collections import defaultdict, dequefrom pathlib import Pathfrom contextlib import asynccontextmanagerfrom fastapi import FastAPI, UploadFile, File, HTTPException, Depends, Headerfrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import FileResponse, StreamingResponsefrom pydantic import BaseModelfrom dotenv import load_dotenvfrom starlette.concurrency import run_in_threadpoolfrom ingest import ingest_pdf, remove_pdf, load_vector_store, DOCUMENTS_PATH, IMAGES_PATHfrom rag import build_engineimport db19 unmodified linesapp = FastAPI(title="Docent AI β Policy Chatbot", lifespan=lifespan)# 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 ----------3 unmodified linessession_id: str | None = Noneclass RenameRequest(BaseModel):title: strclass 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 Falsedq.append(now)return True# ---------- Auth dependency ----------async def get_current_user(authorization: str | None = Header(default=None)):6 unmodified linesreturn userasync 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 userdef _attach_image_urls(sources: list[dict]) -> list[dict]:for src in sources:src["image_urls"] = [f"/images/{fname}" for fname in src.get("images", [])]2 unmodified lines# ---------- Routes ----------# HTML must always revalidate β stale cached pages point at old JS/CSS_NO_CACHE = {"Cache-Control": "no-cache"}@app.get("/")async def root():return FileResponse(str(FRONTEND_PATH / "index.html"), headers=_NO_CACHE)@app.get("/config")6 unmodified lines}@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:6 unmodified linescontinuedest = DOCUMENTS_PATH / upload.filenameif dest.exists():# Re-ingesting would add duplicate chunks to the FAISS indexresults.append({"file": upload.filename, "status": "skipped β already ingested"})continuewith 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 behindresults.append({"file": upload.filename, "status": f"error: {e}"})refresh_rag()1 unmodified line@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"1 unmodified linereturn {"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("/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")18 unmodified linesreturn {"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,17 unmodified linesdb.add_message(session_id, "user", req.question)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 = Noneif answer.strip():saved = db.add_message(session_id, "assistant", answer, 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"},)
123452 unmodified lines8910111213141516171819202119 unmodified lines414243444546474849505110 unmodified lines62636465666768697071727374757677787980818283848586878889909192939495969798991001011023 unmodified lines1061071081091101111124 unmodified lines117118119120121122123124125126127128129130131132133134135136137138import osimport jsonfrom pathlib import Pathfrom dotenv import load_dotenvfrom langchain_nvidia_ai_endpoints import ChatNVIDIA2 unmodified linesfrom langchain_core.output_parsers import StrOutputParserfrom langchain_community.vectorstores import FAISSload_dotenv(Path(__file__).parent.parent / ".env")# A larger instruction-tuned model gives noticeably better policy reasoning and# more reliable "I don't know" refusals than the 8B model. Free on NVIDIA NIM.CHAT_MODEL = os.environ.get("CHAT_MODEL", "meta/llama-3.3-70b-instruct")RETRIEVE_K = 5HISTORY_TURNS = 6 # how many prior messages to feed back as conversation memorySYSTEM_PROMPT = """You are a strict policy assistant. Your ONLY job is to answer questions \using the document excerpts provided below as context.19 unmodified linesIf the question is already standalone, return it unchanged."""def format_docs(docs: list) -> str:parts = []for i, doc in enumerate(docs, 1):source = doc.metadata.get("source", "unknown")page = doc.metadata.get("page", "?")parts.append(f"[Excerpt {i} | File: {source} | Page: {page}]\n{doc.page_content}")return "\n\n---\n\n".join(parts)10 unmodified linesdef _sources_from_docs(docs: list) -> list[dict]:seen = set()sources = []for doc in docs:source = doc.metadata.get("source", "unknown")page = doc.metadata.get("page", "?")key = (source, page)if key in seen:continueseen.add(key)raw_imgs = doc.metadata.get("images", "[]")try:images = json.loads(raw_imgs) if isinstance(raw_imgs, str) else raw_imgsexcept Exception:images = []sources.append({"file": source, "page": page, "images": images})return sourcesclass RagEngine:"""Holds the retriever + LLM and answers questions with optional memory."""def __init__(self, vector_store: FAISS):self.retriever = vector_store.as_retriever(search_type="similarity",search_kwargs={"k": RETRIEVE_K},)self.llm = ChatNVIDIA(model=CHAT_MODEL,api_key=os.environ["NVIDIA_API_KEY"],temperature=0.0,max_tokens=1024,)self.answer_prompt = ChatPromptTemplate.from_messages([("system", SYSTEM_PROMPT),MessagesPlaceholder("history"),("human", "{question}"),])3 unmodified linesMessagesPlaceholder("history"),("human", "{question}"),])self.condense_chain = self.condense_prompt | self.llm | StrOutputParser()def _standalone_question(self, question: str, history_msgs: list) -> str:if not history_msgs:4 unmodified linesexcept Exception:return questiondef answer(self, question: str, history: list[dict] | None = None) -> tuple[str, list[dict]]:"""Return (answer_text, sources). History is a list of {role, content}."""history_msgs = _to_lc_messages(history or [])search_query = self._standalone_question(question, history_msgs)docs = self.retriever.invoke(search_query)context = format_docs(docs)sources = _sources_from_docs(docs)chain = self.answer_prompt | self.llm | StrOutputParser()answer = chain.invoke({"context": context,"history": history_msgs,"question": question,})return answer, sourcesdef build_engine(vector_store: FAISS) -> RagEngine:123456782 unmodified lines111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565719 unmodified lines777879808182838485868788899091929310 unmodified lines1041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562573 unmodified lines2612622632642652662674 unmodified lines272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392import osimport jsonimport reimport timefrom concurrent.futures import ThreadPoolExecutor, TimeoutError as _FutureTimeoutfrom pathlib import Pathfrom dotenv import load_dotenvfrom langchain_nvidia_ai_endpoints import ChatNVIDIA2 unmodified linesfrom langchain_core.output_parsers import StrOutputParserfrom langchain_community.vectorstores import FAISStry:from langchain_nvidia_ai_endpoints import NVIDIARerankexcept ImportError:NVIDIARerank = Nonetry:from rank_bm25 import BM25Okapiexcept ImportError:BM25Okapi = Noneload_dotenv(Path(__file__).parent.parent / ".env")# Nemotron Super 49B: NVIDIA's distillation of Llama 3.3 70B β comparable# answer quality, but its NIM endpoint is far less congested than the raw 70B# (which regularly queues for minutes and 504s on the free tier).CHAT_MODEL = os.environ.get("CHAT_MODEL", "nvidia/llama-3.3-nemotron-super-49b-v1.5")# Question condensing is a trivial rewrite task β a small model does it just as# well and much faster than the 70B answer model.CONDENSE_MODEL = os.environ.get("CONDENSE_MODEL", "meta/llama-3.1-8b-instruct")# Reranker: free on NVIDIA NIM; re-scores the candidate chunks against the# question far more accurately than raw embedding distance. Set USE_RERANKER=0# to disable.RERANK_MODEL = os.environ.get("RERANK_MODEL", "nvidia/llama-nemotron-rerank-1b-v2")USE_RERANKER = os.environ.get("USE_RERANKER", "1").lower() not in ("0", "false", "no")# If the primary model streams nothing for this long, give up and answer with# the fallback model instead of waiting for NVIDIA's 300s gateway timeout.FIRST_TOKEN_TIMEOUT = float(os.environ.get("FIRST_TOKEN_TIMEOUT", "25"))RETRIEVE_K = 5 # chunks that reach the promptCANDIDATE_K = 20 # candidates gathered before fusion/rerankingRRF_C = 60 # standard reciprocal-rank-fusion constantHISTORY_TURNS = 6 # how many prior messages to feed back as conversation memory# Words that suggest the question leans on the conversation ("it", "that# policy", "what about them"...). Only such questions need the condense step._REFERENTIAL = re.compile(r"\b(it|its|that|this|these|those|they|them|their|he|she|him|her|his|hers"r"|one|ones|same|above|previous|earlier|before|again|also|too|more|another"r"|other|why|and)\b",re.IGNORECASE,)SYSTEM_PROMPT = """You are a strict policy assistant. Your ONLY job is to answer questions \using the document excerpts provided below as context.19 unmodified linesIf the question is already standalone, return it unchanged."""def _display_page(page) -> int | str:"""PyPDFLoader stores 0-based page numbers; convert to the 1-based numbera human (and any PDF viewer) uses."""return page + 1 if isinstance(page, int) else "?"def format_docs(docs: list) -> str:parts = []for i, doc in enumerate(docs, 1):source = doc.metadata.get("source", "unknown")page = _display_page(doc.metadata.get("page"))parts.append(f"[Excerpt {i} | File: {source} | Page: {page}]\n{doc.page_content}")return "\n\n---\n\n".join(parts)10 unmodified linesdef _sources_from_docs(docs: list) -> list[dict]:by_key: dict = {}sources = []for doc in docs:source = doc.metadata.get("source", "unknown")page = _display_page(doc.metadata.get("page"))snippet = (doc.page_content or "").strip()key = (source, page)if key in by_key:# Same file+page retrieved more than once β keep every snippet so# the PDF preview can highlight all matched passages.if snippet:by_key[key]["snippets"].append(snippet)continueraw_imgs = doc.metadata.get("images", "[]")try:images = json.loads(raw_imgs) if isinstance(raw_imgs, str) else raw_imgsexcept Exception:images = []entry = {"file": source,"page": page,"images": images,"snippets": [snippet] if snippet else [],}by_key[key] = entrysources.append(entry)return sources# Crude suffix stripping so "plagiarizing" and "plagiarism" both become# "plagiar" β enough for BM25 recall without a full stemmer dependency._STEM_SUFFIXES = ("izations", "ization", "isation", "izing", "ising", "ments", "ment","ations", "ation", "ness", "isms", "ism", "izes", "ize", "ise","ying", "ing", "ies", "ied", "ers", "er", "est", "es", "ed", "ly", "s", "y",)def _stem(word: str) -> str:for suffix in _STEM_SUFFIXES:if len(word) > len(suffix) + 3 and word.endswith(suffix):return word[: -len(suffix)]return worddef _bm25_tokenize(text: str) -> list[str]:return [_stem(w) for w in re.findall(r"[a-z0-9]+", text.lower())]def _doc_key(doc) -> tuple:return (doc.metadata.get("source"), doc.metadata.get("page"), hash(doc.page_content))# Sentinel marking a stream that ended without producing any token_STREAM_END = object()def _first_visible_token(gen):"""Advance the stream to the first NON-EMPTY token. Reasoning models emitempty-content chunks while 'thinking' β those must not satisfy thefirst-token watchdog, or a silently-thinking model looks like a hung UI."""for token in gen:if token:return tokenreturn _STREAM_ENDdef _answer_system_prompt(model_name: str) -> str:"""Nemotron reasoning models stream hidden 'thinking' tokens by default βthe UI sees nothing for 20-40s and the token budget gets eaten. /no_thinkat the top of the system prompt disables that."""if "nemotron" in model_name.lower():return "/no_think\n" + SYSTEM_PROMPTreturn SYSTEM_PROMPTdef _needs_condensing(question: str, history_msgs: list) -> bool:"""Skip the condense LLM call when the question stands on its own.Very short questions or ones with referential words need the history."""if not history_msgs:return Falseq = question.strip()return len(q.split()) <= 4 or bool(_REFERENTIAL.search(q))class RagEngine:"""Holds the retriever + LLM and answers questions with optional memory."""def __init__(self, vector_store: FAISS):self.vector_store = vector_store# Keyword (BM25) index over every chunk β catches exact tokens like# policy codes ("A011") and acronyms that embeddings often miss.self._all_docs = list(getattr(vector_store.docstore, "_dict", {}).values())self._bm25 = Noneif BM25Okapi is not None and self._all_docs:# Index the source filename with each chunk β policy titles like# "Plagiarism-Policy" are a strong keyword signal the chunk text# itself often lacks.self._bm25 = BM25Okapi([_bm25_tokenize(f"{d.metadata.get('source', '')} {d.page_content}")for d in self._all_docs])self.reranker = Noneself._rerank_failures = 0if NVIDIARerank is not None and USE_RERANKER:try:self.reranker = NVIDIARerank(model=RERANK_MODEL,api_key=os.environ["NVIDIA_API_KEY"],top_n=RETRIEVE_K,)except Exception as e:print(f"[rag] reranker unavailable: {e}", flush=True)self.llm = ChatNVIDIA(model=CHAT_MODEL,api_key=os.environ["NVIDIA_API_KEY"],temperature=0.0,max_tokens=1024,)self.condense_llm = ChatNVIDIA(model=CONDENSE_MODEL,api_key=os.environ["NVIDIA_API_KEY"],temperature=0.0,max_tokens=120,)# Backup answer model: NVIDIA's free 70B endpoint sometimes 504s under# load; the 8B model is far less congested and still grounded by the# strict context-only prompt.self.fallback_llm = ChatNVIDIA(model=CONDENSE_MODEL,api_key=os.environ["NVIDIA_API_KEY"],temperature=0.0,max_tokens=1024,)self.answer_prompt = ChatPromptTemplate.from_messages([("system", _answer_system_prompt(CHAT_MODEL)),MessagesPlaceholder("history"),("human", "{question}"),])self.fallback_prompt = ChatPromptTemplate.from_messages([("system", _answer_system_prompt(CONDENSE_MODEL)),MessagesPlaceholder("history"),("human", "{question}"),])3 unmodified linesMessagesPlaceholder("history"),("human", "{question}"),])self.condense_chain = self.condense_prompt | self.condense_llm | StrOutputParser()def _standalone_question(self, question: str, history_msgs: list) -> str:if not history_msgs:4 unmodified linesexcept Exception:return questiondef _retrieve(self, query: str) -> list:"""Hybrid retrieval: vector + BM25 merged with reciprocal-rank fusion,then (optionally) reranked by a cross-encoder for final precision."""rrf: dict[tuple, float] = {}by_key: dict[tuple, object] = {}for rank, doc in enumerate(self.vector_store.similarity_search(query, k=CANDIDATE_K)):key = _doc_key(doc)by_key[key] = docrrf[key] = rrf.get(key, 0.0) + 1.0 / (RRF_C + rank)if self._bm25 is not None:scores = self._bm25.get_scores(_bm25_tokenize(query))top_idx = sorted(range(len(scores)), key=lambda i: -scores[i])[:CANDIDATE_K]for rank, i in enumerate(top_idx):if scores[i] <= 0:breakdoc = self._all_docs[i]key = _doc_key(doc)by_key.setdefault(key, doc)rrf[key] = rrf.get(key, 0.0) + 1.0 / (RRF_C + rank)# RRF gives the fallback ordering; the reranker sees the FULL union of# both retrievers' candidates (~2ΓCANDIDATE_K) β it judges relevance# far better than rank fusion, so don't pre-cut its input.candidates = [by_key[k] for k in sorted(rrf, key=lambda k: -rrf[k])]if not candidates:return []if self.reranker is not None:try:result = list(self.reranker.compress_documents(documents=candidates, query=query))self._rerank_failures = 0return resultexcept Exception as e:# Tolerate transient blips; only give up after repeated failuresself._rerank_failures += 1if self._rerank_failures >= 3:print(f"[rag] reranker failed {self._rerank_failures}x ({e.__class__.__name__}) β disabled", flush=True)self.reranker = Noneelse:print(f"[rag] reranker error ({e.__class__.__name__}) β using fusion ranking this time", flush=True)return candidates[:RETRIEVE_K]def _prepare(self, question: str, history: list[dict] | None):"""Shared retrieval pipeline: returns (chain_inputs, sources)."""history_msgs = _to_lc_messages(history or [])t0 = time.perf_counter()if _needs_condensing(question, history_msgs):search_query = self._standalone_question(question, history_msgs)else:search_query = questiont1 = time.perf_counter()docs = self._retrieve(search_query)t2 = time.perf_counter()print(f"[rag] condense {t1 - t0:.2f}s | retrieve {t2 - t1:.2f}s "f"| {len(docs)} chunks | query: {search_query[:80]!r}",flush=True,)inputs = {"context": format_docs(docs),"history": history_msgs,"question": question,}return inputs, _sources_from_docs(docs)def _stream_with_fallback(self, inputs: dict):"""Stream from the main model; if it errors OR produces no outputwithin FIRST_TOKEN_TIMEOUT (a congested free endpoint can hang for300s before 504ing), answer with the smaller fallback model instead."""primary = (self.answer_prompt | self.llm | StrOutputParser()).stream(inputs)executor = ThreadPoolExecutor(max_workers=1)future = executor.submit(_first_visible_token, primary)try:first = future.result(timeout=FIRST_TOKEN_TIMEOUT)except _FutureTimeout:print(f"[rag] {CHAT_MODEL} gave no output within {FIRST_TOKEN_TIMEOUT:.0f}s β "f"answering with {CONDENSE_MODEL}",flush=True,)executor.shutdown(wait=False)yield from (self.fallback_prompt | self.fallback_llm | StrOutputParser()).stream(inputs)returnexcept Exception as e:print(f"[rag] {CHAT_MODEL} failed ({e.__class__.__name__}) β "f"retrying with {CONDENSE_MODEL}",flush=True,)executor.shutdown(wait=False)yield from (self.fallback_prompt | self.fallback_llm | StrOutputParser()).stream(inputs)returnexecutor.shutdown(wait=False)if first is _STREAM_END:returnyield firstyield from primarydef answer(self, question: str, history: list[dict] | None = None) -> tuple[str, list[dict]]:"""Return (answer_text, sources). History is a list of {role, content}."""inputs, sources = self._prepare(question, history)return "".join(self._stream_with_fallback(inputs)), sourcesdef answer_stream(self, question: str, history: list[dict] | None = None):"""Return (sources, token_generator) so the caller can stream the answer."""inputs, sources = self._prepare(question, history)return sources, self._stream_with_fallback(inputs)def build_engine(vector_store: FAISS) -> RagEngine:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162[ { "question": "What happens if a student is caught plagiarizing?", "expected_files": ["Plagiarism-Policy-of-SSUET.pdf"] }, { "question": "What is the attendance requirement for online classes?", "expected_files": ["A21-Attendance-Policy-for-Online-Classes-Fall-2020-1-converted.pdf", "Policy-and-Procedures-for-online-education-1.pdf"] }, { "question": "How can I transfer my credit hours from another university?", "expected_files": ["A024-Policy-for-Transfer-of-Credit-Hours-Student-Mobility-12-08-2021-min.pdf", "Migration-Policy.pdf"] }, { "question": "What are the requirements to complete a PhD degree?", "expected_files": ["A08-Rules-and-Regulations-for-the-degree-of-PhD-V5.pdf", "SSUET-PhD-Policy-Ver-8-For-Batches-2024-Spring-and-Onwards.pdf"] }, { "question": "What is the admission process for the 2024-2025 academic year?", "expected_files": ["Admission-Policy-2024-2025.pdf"] }, { "question": "What support is available for students with disabilities?", "expected_files": ["G03-Policy-for-Students-with-Disabilities-V2-12-08-2021-min.pdf"] }, { "question": "Is smoking or tobacco use allowed on campus?", "expected_files": ["G025-Policy-Against-Drug-and-Tobacco-Abuse-at-SSUET-12-08-2021-min.pdf", "G025-Policy-Against-Drug-and-Tobacco-Abuse-at-SSUET-12-08-2021-min (1).pdf", "Smoking-Undertaking-Students.pdf"] }, { "question": "How is the GPA calculated and what are the grade boundaries?", "expected_files": ["Grading-System.pdf", "Academic-Rules-Regulations.pdf"] }, { "question": "What is the fee refund policy?", "expected_files": ["HEC-Refund-Policy-2024.pdf"] }, { "question": "How does the internship program work for students?", "expected_files": ["A028-Internship-Policy-and-Mechanism-V1.pdf", "G024-Policy-and-Procedure-for-Engaging-Interns.pdf"] }, { "question": "What is the procedure for reporting sexual harassment?", "expected_files": ["Amendment_Policy_Sexual_Harassment-ACT-2022.pdf", "protection-agaainst-harassment-of-women-at-the-workplace-2010.pdf", "Members-of-Inquiry-Committee-for-Protection-against-Sexual-Harassment-at-SSUET.pdf"] }, { "question": "What are the rules for university transport services?", "expected_files": ["Transport-Policy-V1.pdf"] }, { "question": "How do students appeal against a decision?", "expected_files": ["Appeals-Procedure-Policy.pdf", "Policy-Procedures-for-Resolving-Grievances.pdf"] }, { "question": "What is the honorarium for publishing a research paper?", "expected_files": ["Research-Honorarium-and-Conference-Assistance-Policy-V2.pdf", "A011-Research-Honorarium-and-Conference-Assistance-Policy-V3.pdf", "Application-Form-for-Publication-Honorarium-1-converted.pdf"] }, { "question": "What is the role of an academic advisor?", "expected_files": ["A026-Policy-for-Role-and-Responsibility-of-Academic-Advisor-V1.pdf"] }]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182"""Retrieval evaluation for Docent AI.
For each question in eval_questions.json, runs the full retrieval pipeline(hybrid BM25 + vector search + reranker) and checks whether a chunk from oneof the expected source PDFs appears in the results.
Reports: - hit@k : fraction of questions where an expected file was retrieved - MRR : mean reciprocal rank of the first expected file
Usage (from the project root): py evaluate.py"""import jsonimport sysimport timefrom pathlib import Path
sys.path.insert(0, str(Path(__file__).parent / "backend"))
from ingest import load_vector_store # noqa: E402from rag import build_engine, RETRIEVE_K # noqa: E402
EVAL_FILE = Path(__file__).parent / "eval_questions.json"
def retrieve_with_retry(engine, question: str, attempts: int = 3): """The free NVIDIA endpoints occasionally return transient 5xx errors.""" for i in range(attempts): try: return engine._retrieve(question) except Exception as e: if i == attempts - 1: raise print(f" (transient {e.__class__.__name__} β retrying in 3s)") time.sleep(3)
def main() -> None: cases = json.loads(EVAL_FILE.read_text(encoding="utf-8"))
store = load_vector_store() if store is None: print("No FAISS index found β ingest some PDFs first.") sys.exit(1)
engine = build_engine(store)
hits = 0 reciprocal_ranks = [] print(f"Evaluating {len(cases)} questions (k={RETRIEVE_K})\n")
for case in cases: question = case["question"] expected = set(case["expected_files"])
docs = retrieve_with_retry(engine, question) retrieved = [d.metadata.get("source", "?") for d in docs]
rank = next( (i + 1 for i, f in enumerate(retrieved) if f in expected), None, ) if rank is not None: hits += 1 reciprocal_ranks.append(1.0 / rank) print(f" HIT @{rank} {question}") else: reciprocal_ranks.append(0.0) print(f" MISS {question}") print(f" expected : {sorted(expected)}") print(f" retrieved: {retrieved}")
n = len(cases) print("\n" + "=" * 60) print(f"hit@{RETRIEVE_K} : {hits}/{n} ({hits / n:.0%})") print(f"MRR : {sum(reciprocal_ranks) / n:.3f}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Docent AI β Admin Dashboard</title> <script> (function () { var t = localStorage.getItem('docent-theme'); if (t) document.documentElement.dataset.theme = t; })(); </script> <script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script> <style> *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } :root { color-scheme: dark; --bg: #0f1117; --bg2: #131722; --surface: #1a1d27; --surface2: #22263a; --border: #2e3350; --accent: #76b900; --accent-dk: #5c9100; --accent-tint: rgba(118, 185, 0, .12); --text: #e8eaf0; --text-muted: #8b90a8; --hover: #272c43; --scroll-thumb: #2e3350; --warn: #ffb84d; --warn-tint: rgba(255, 184, 77, .12); --danger: #e74c3c; --radius: 16px; --font: 'Segoe UI', system-ui, sans-serif; --shadow: 0 8px 28px rgba(0, 0, 0, .28); } [data-theme="light"] { color-scheme: light; --bg: #eef1f6; --bg2: #e6ebf3; --surface: #ffffff; --surface2: #f1f3f8; --border: #d7dce6; --accent: #6aa800; --accent-dk: #578a00; --accent-tint: rgba(106, 168, 0, .12); --text: #1c2130; --text-muted: #68708a; --hover: #e5e9f2; --scroll-thumb: #c3cad8; --warn: #c07c00; --warn-tint: rgba(192, 124, 0, .1); --shadow: 0 8px 28px rgba(30, 40, 70, .09); }
body { font-family: var(--font); color: var(--text); min-height: 100vh; background: radial-gradient(1200px 500px at 80% -10%, var(--accent-tint), transparent), linear-gradient(180deg, var(--bg2), var(--bg) 320px); transition: color .25s; }
* { scrollbar-width: thin; scrollbar-color: var(--scroll-thumb) transparent; } ::-webkit-scrollbar { width: 8px; height: 8px; } ::-webkit-scrollbar-track { background: transparent; } ::-webkit-scrollbar-thumb { background: var(--scroll-thumb); border-radius: 4px; } ::-webkit-scrollbar-thumb:hover { background: var(--accent); }
/* ββ Top bar ββ */ .topbar { display: flex; align-items: center; gap: 14px; padding: 14px 30px; background: color-mix(in srgb, var(--surface) 82%, transparent); backdrop-filter: blur(10px); border-bottom: 1px solid var(--border); position: sticky; top: 0; z-index: 5; } .brand-tile { width: 40px; height: 40px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; background: linear-gradient(135deg, var(--accent), var(--accent-dk)); border-radius: 12px; color: #000; font-size: 1.05rem; box-shadow: 0 4px 14px var(--accent-tint); } .topbar-text { flex: 1; min-width: 0; } .topbar h1 { font-size: 1.05rem; font-weight: 700; letter-spacing: .02em; } .topbar .sub { font-size: .72rem; color: var(--text-muted); }
.btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; height: 40px; padding: 0 18px; font-size: .84rem; font-weight: 600; font-family: var(--font); border-radius: 999px; cursor: pointer; text-decoration: none; transition: background .2s, border-color .2s, color .2s, transform .12s; flex-shrink: 0; } .btn:active { transform: scale(.97); } .btn-accent { background: var(--accent); color: #000; border: 1px solid var(--accent); } .btn-accent:hover { background: var(--accent-dk); border-color: var(--accent-dk); } .btn-ghost { background: transparent; color: var(--text); border: 1px solid var(--border); } .btn-ghost:hover { border-color: var(--accent); color: var(--accent); } .btn.icon-only { width: 40px; padding: 0; } .btn svg { width: 17px; height: 17px; }
.wrap { max-width: 1160px; margin: 0 auto; padding: 30px 22px 70px; }
.state { text-align: center; color: var(--text-muted); padding: 100px 20px; font-size: .95rem; } .state a { color: var(--accent); }
/* ββ Page head row ββ */ .page-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 20px; flex-wrap: wrap; } .page-head h2 { font-size: 1.3rem; font-weight: 700; } .page-head .updated { font-size: .74rem; color: var(--text-muted); }
/* ββ Stat cards ββ */ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 14px; } .card { display: flex; align-items: center; gap: 14px; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 18px; box-shadow: var(--shadow); transition: transform .15s, border-color .15s; } .card:hover { transform: translateY(-3px); border-color: var(--accent); } .card .tile { width: 46px; height: 46px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; background: var(--accent-tint); border-radius: 13px; font-size: 1.25rem; } .card.warn .tile { background: var(--warn-tint); } .card .value { font-size: 1.6rem; font-weight: 700; color: var(--text); line-height: 1.15; } .card.warn .value { color: var(--warn); } .card .label { font-size: .7rem; color: var(--text-muted); letter-spacing: .07em; text-transform: uppercase; }
/* ββ Panels ββ */ .panel { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 24px; margin-top: 20px; box-shadow: var(--shadow); } .panel-head { display: flex; align-items: center; gap: 10px; margin-bottom: 18px; } .panel-head .p-ico { width: 30px; height: 30px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; background: var(--accent-tint); border-radius: 9px; font-size: .95rem; } .panel-head h3 { font-size: .95rem; font-weight: 700; flex: 1; } .panel-head .hint { font-size: .72rem; color: var(--text-muted); }
.two-col { display: grid; grid-template-columns: 3fr 2fr; gap: 20px; margin-top: 20px; } .two-col .panel { margin-top: 0; } @media (max-width: 860px) { .two-col { grid-template-columns: 1fr; } }
/* ββ Daily activity chart ββ */ .chart { display: flex; align-items: flex-end; gap: 7px; height: 170px; padding-top: 24px; border-bottom: 1px solid var(--border); } .chart .col { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 7px; height: 100%; justify-content: flex-end; } .chart .bar { width: 100%; max-width: 42px; border-radius: 7px 7px 0 0; background: linear-gradient(180deg, var(--accent), var(--accent-dk)); min-height: 3px; position: relative; cursor: default; transition: filter .15s; } .chart .bar.zero { background: var(--surface2); } .chart .bar:hover { filter: brightness(1.2); } .chart .bar .n { position: absolute; top: -20px; left: 50%; transform: translateX(-50%); font-size: .68rem; color: var(--text); font-weight: 700; } .chart-days { display: flex; gap: 7px; margin-top: 8px; } .chart-days span { flex: 1; text-align: center; font-size: .62rem; color: var(--text-muted); white-space: nowrap; }
/* ββ Cited docs bars ββ */ .hbar-row { display: flex; align-items: center; gap: 10px; margin-bottom: 11px; } .hbar-name { flex: 0 0 44%; font-size: .78rem; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .hbar-track { flex: 1; background: var(--surface2); border-radius: 8px; height: 16px; overflow: hidden; } .hbar-fill { height: 100%; background: linear-gradient(90deg, var(--accent-dk), var(--accent)); border-radius: 8px; transition: width .6s cubic-bezier(.2, .8, .3, 1); } .hbar-count { flex: 0 0 34px; font-size: .78rem; color: var(--accent); font-weight: 700; text-align: right; }
/* ββ Feedback ββ */ .fb-split { display: flex; height: 18px; border-radius: 9px; overflow: hidden; background: var(--surface2); margin-bottom: 10px; } .fb-up { background: linear-gradient(90deg, var(--accent-dk), var(--accent)); transition: width .6s; } .fb-down { background: var(--danger); transition: width .6s; } .fb-legend { display: flex; justify-content: space-between; font-size: .78rem; color: var(--text-muted); }
/* ββ Lists ββ */ .qlist { list-style: none; display: flex; flex-direction: column; gap: 9px; } .qlist li { font-size: .84rem; padding: 11px 14px; background: var(--surface2); border-radius: 10px; border-left: 3px solid var(--warn); line-height: 1.5; word-break: break-word; } .qlist li.empty { border-left-color: var(--border); color: var(--text-muted); font-style: italic; }
.doclist { list-style: none; display: flex; flex-direction: column; gap: 7px; max-height: 280px; overflow-y: auto; padding-right: 4px; } .doclist li { font-size: .78rem; padding: 8px 11px; background: var(--surface2); border-radius: 9px; border-left: 3px solid var(--accent); word-break: break-all; transition: background .15s; } .doclist li:hover { background: var(--hover); } .hidden { display: none !important; } </style></head><body>
<header class="topbar"> <span class="brand-tile">◆</span> <div class="topbar-text"> <h1>Admin Dashboard</h1> <p class="sub">Docent AI β usage analytics & knowledge-base health</p> </div> <button class="btn btn-ghost icon-only" id="themeBtn" type="button" title="Toggle light/dark mode"></button> <button class="btn btn-ghost icon-only" id="refreshBtn" type="button" title="Refresh data"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M23 4v6h-6M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg> </button> <a class="btn btn-accent" href="/"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5M12 19l-7-7 7-7"/></svg> Back to chat </a> </header>
<div class="wrap"> <div class="state" id="state">Loading dashboardβ¦</div>
<div id="dash" class="hidden"> <div class="page-head"> <h2>Overview</h2> <span class="updated" id="updatedAt"></span> </div>
<div class="grid" id="statGrid"></div>
<div class="panel"> <div class="panel-head"> <span class="p-ico">📈</span> <h3>Questions per day</h3> <span class="hint">last 14 days</span> </div> <div class="chart" id="chart"></div> <div class="chart-days" id="chartDays"></div> </div>
<div class="two-col"> <div class="panel"> <div class="panel-head"> <span class="p-ico">📄</span> <h3>Most cited documents</h3> </div> <div id="citedBars"></div> </div> <div class="panel"> <div class="panel-head"> <span class="p-ico">👍</span> <h3>Answer feedback</h3> </div> <div class="fb-split" id="fbSplit"></div> <div class="fb-legend" id="fbLegend"></div>
<div class="panel-head" style="margin-top:26px"> <span class="p-ico">📚</span> <h3>Knowledge base</h3> <span class="hint" id="docCount"></span> </div> <ul class="doclist" id="docList"></ul> </div> </div>
<div class="panel"> <div class="panel-head"> <span class="p-ico">❓</span> <h3>Questions the bot could not answer</h3> <span class="hint">candidates for missing policies</span> </div> <ul class="qlist" id="unansweredList"></ul> </div> </div> </div>
<script> const stateEl = document.getElementById('state'); const dashEl = document.getElementById('dash'); let sb = null;
/* Theme toggle (shared localStorage key with the chat app) */ const themeBtn = document.getElementById('themeBtn'); const ICON_SUN = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>`; const ICON_MOON = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>`;
function applyTheme(theme) { document.documentElement.dataset.theme = theme; localStorage.setItem('docent-theme', theme); themeBtn.innerHTML = theme === 'light' ? ICON_MOON : ICON_SUN; } themeBtn.addEventListener('click', () => applyTheme(document.documentElement.dataset.theme === 'light' ? 'dark' : 'light')); applyTheme(localStorage.getItem('docent-theme') || 'dark');
document.getElementById('refreshBtn').addEventListener('click', () => loadData());
function esc(s) { return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); }
async function authedFetch(url) { const { data } = await sb.auth.getSession(); const token = data.session ? data.session.access_token : null; return fetch(url, { headers: token ? { Authorization: `Bearer ${token}` } : {} }); }
function card(icon, label, value, warn = false) { return `<div class="card${warn ? ' warn' : ''}"> <span class="tile">${icon}</span> <div> <div class="value">${value}</div> <div class="label">${label}</div> </div> </div>`; }
function render(a, docs) { document.getElementById('statGrid').innerHTML = card('💬', 'Questions asked', a.total_questions ?? 0) + card('👥', 'Conversations', a.total_conversations ?? 0) + card('📄', 'Documents', a.total_documents ?? 0) + card('🧩', 'Indexed chunks', a.total_chunks ?? 0) + card('❓', 'Unanswered', a.unanswered_count ?? 0, (a.unanswered_count ?? 0) > 0);
// Daily chart const daily = a.daily_questions || []; const max = Math.max(1, ...daily.map(d => d.count)); document.getElementById('chart').innerHTML = daily.map(d => ` <div class="col"> <div class="bar${d.count ? '' : ' zero'}" style="height:${Math.max(2, Math.round((d.count / max) * 100))}%" title="${d.date}: ${d.count} question${d.count === 1 ? '' : 's'}"> ${d.count ? `<span class="n">${d.count}</span>` : ''} </div> </div>`).join(''); document.getElementById('chartDays').innerHTML = daily.map(d => `<span>${d.date.slice(5)}</span>`).join('');
// Cited documents const cited = a.top_documents || []; const cmax = Math.max(1, ...cited.map(d => d.citations)); document.getElementById('citedBars').innerHTML = cited.length ? cited.map(d => ` <div class="hbar-row"> <span class="hbar-name" title="${esc(d.file)}">${esc(d.file)}</span> <div class="hbar-track"><div class="hbar-fill" style="width:${Math.round((d.citations / cmax) * 100)}%"></div></div> <span class="hbar-count">${d.citations}</span> </div>`).join('') : '<p style="font-size:.8rem;color:var(--text-muted);font-style:italic">No citations yet.</p>';
// Feedback split const up = a.feedback?.up ?? 0, down = a.feedback?.down ?? 0, total = up + down; const upPct = total ? Math.round((up / total) * 100) : 50; document.getElementById('fbSplit').innerHTML = `<div class="fb-up" style="width:${total ? upPct : 0}%"></div><div class="fb-down" style="width:${total ? 100 - upPct : 0}%"></div>`; document.getElementById('fbLegend').innerHTML = total ? `<span>👍 ${up} helpful (${upPct}%)</span><span>👎 ${down} not helpful</span>` : '<span>No feedback yet</span>';
// Documents document.getElementById('docCount').textContent = `${(docs || []).length} files`; document.getElementById('docList').innerHTML = (docs || []).map(d => `<li>${esc(d)}</li>`).join('') || '<li style="border-left-color:var(--border);color:var(--text-muted);font-style:italic">No documents ingested</li>';
// Unanswered document.getElementById('unansweredList').innerHTML = (a.recent_unanswered || []).map(q => `<li>${esc(q)}</li>`).join('') || '<li class="empty">None β every question found an answer in the documents.</li>';
document.getElementById('updatedAt').textContent = `Updated ${new Date().toLocaleTimeString()}`; stateEl.classList.add('hidden'); dashEl.classList.remove('hidden'); }
async function loadData() { const [aRes, dRes] = await Promise.all([authedFetch('/analytics'), authedFetch('/documents')]); if (!aRes.ok) throw new Error('Could not load analytics.'); const analytics = await aRes.json(); const docs = dRes.ok ? (await dRes.json()).documents : []; render(analytics, docs); }
async function boot() { try { const cfg = await (await fetch('/config')).json(); if (!cfg.configured || !window.supabase) throw new Error('Server not configured.'); sb = window.supabase.createClient(cfg.supabaseUrl, cfg.supabaseAnonKey);
const { data } = await sb.auth.getSession(); if (!data.session) { stateEl.innerHTML = 'You are not logged in. <a href="/">Go to the app</a> and log in as an admin first.'; return; }
const meRes = await authedFetch('/me'); const me = await meRes.json(); if (!me.is_admin) { stateEl.innerHTML = 'This dashboard is for admins only. <a href="/">Back to chat</a>'; return; }
await loadData(); } catch (err) { stateEl.innerHTML = `${esc(err.message || 'Could not load the dashboard.')} <a href="/">Back to chat</a>`; } }
boot(); </script></body></html>3 unmodified lines45678910114 unmodified lines1617181920211 unmodified line2324252627282930313233343536373839404142434426 unmodified lines7172737475767715 unmodified lines93949596979811 unmodified lines1101111121131141156 unmodified lines1221231241251261279 unmodified lines1371381391401411423 unmodified lines<meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Docent AI β Policy Assistant</title><link rel="stylesheet" href="/static/style.css?v=4" /><script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script></head><body>4 unmodified lines<!-- ββ Auth gate ββ --><div class="auth-overlay hidden" id="authOverlay"><div class="auth-card"><div class="auth-brand"><span class="logo-icon">◆</span>1 unmodified line</div><p class="auth-sub">Sign in to your policy assistant</p><div class="auth-tabs"><button class="auth-tab active" id="tabLogin" type="button">Log in</button><button class="auth-tab" id="tabSignup" type="button">Sign up</button></div><form class="auth-form" id="authForm" autocomplete="on"><label class="auth-label">Email</label><input type="email" id="authEmail" class="auth-input" placeholder="you@example.com" required /><label class="auth-label">Password</label><input type="password" id="authPassword" class="auth-input" placeholder="β’β’β’β’β’β’β’β’" minlength="6" required /><button type="submit" class="auth-submit" id="authSubmit"><span id="authSubmitText">Log in</span><span id="authSpinner" class="spinner hidden"></span></button><div id="authMessage" class="auth-message hidden"></div></form></div>26 unmodified lines</ul></div><details class="upload-details"><summary class="section-label">Documents</summary><div class="upload-section"><label class="drop-zone" id="dropZone">15 unmodified lines</div></details><div class="sidebar-footer"><div class="account"><span class="account-email" id="accountEmail">β</span>11 unmodified lines<h1 id="chatTitle">Policy Chatbot</h1><p>Ask anything about the uploaded policy documents.</p></div></header><div class="messages" id="messages">6 unmodified lines</div><form class="input-bar" id="chatForm" autocomplete="off"><textareaid="questionInput"class="question-input"9 unmodified lines</div><script src="/static/script.js?v=4"></script></body></html>3 unmodified lines4567891011121314151617181920214 unmodified lines262728293031321 unmodified line34353637383940414243444546474849505152535455565758596026 unmodified lines8788899091929315 unmodified lines10911011111211311411511611711811 unmodified lines1301311321331341351361376 unmodified lines1441451461471481491509 unmodified lines1601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901913 unmodified lines<meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Docent AI β Policy Assistant</title><script>// Apply the saved theme before first paint to avoid a flash(function () {var t = localStorage.getItem('docent-theme');if (t) document.documentElement.dataset.theme = t;})();</script><link rel="stylesheet" href="/static/style.css?v=11" /><script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script><script src="https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.min.js"></script><script src="https://cdn.jsdelivr.net/npm/marked@12/marked.min.js"></script><script src="https://cdn.jsdelivr.net/npm/dompurify@3/dist/purify.min.js"></script></head><body>4 unmodified lines<!-- ββ Auth gate ββ --><div class="auth-overlay hidden" id="authOverlay"><button type="button" class="theme-fab" id="themeBtnAuth" title="Toggle light/dark mode"></button><div class="auth-card"><div class="auth-brand"><span class="logo-icon">◆</span>1 unmodified line</div><p class="auth-sub">Sign in to your policy assistant</p><div class="auth-tabs" id="authTabs"><button class="auth-tab active" id="tabLogin" type="button">Log in</button><button class="auth-tab" id="tabSignup" type="button">Sign up</button></div><form class="auth-form" id="authForm" autocomplete="on"><label class="auth-label" id="authEmailLabel">Email</label><input type="email" id="authEmail" class="auth-input" placeholder="you@example.com" required /><label class="auth-label" id="authPasswordLabel">Password</label><div class="password-wrap" id="passwordWrap"><input type="password" id="authPassword" class="auth-input" placeholder="β’β’β’β’β’β’β’β’" minlength="6" required /><button type="button" class="eye-btn" id="togglePw" title="Show password" tabindex="-1"></button></div><button type="submit" class="auth-submit" id="authSubmit"><span id="authSubmitText">Log in</span><span id="authSpinner" class="spinner hidden"></span></button><button type="button" class="auth-link" id="forgotBtn">Forgot password?</button><button type="button" class="auth-link hidden" id="backToLogin">← Back to log in</button><div id="authMessage" class="auth-message hidden"></div></form></div>26 unmodified lines</ul></div><details class="upload-details hidden" id="uploadPanel"><summary class="section-label">Documents</summary><div class="upload-section"><label class="drop-zone" id="dropZone">15 unmodified lines</div></details><button class="btn-analytics hidden" id="analyticsBtn" type="button">📊 Analytics</button><div class="sidebar-footer"><div class="account"><span class="account-email" id="accountEmail">β</span>11 unmodified lines<h1 id="chatTitle">Policy Chatbot</h1><p>Ask anything about the uploaded policy documents.</p></div><button class="header-btn hidden" id="exportBtn" type="button" title="Export conversation as text">⬇</button><button class="header-btn" id="themeBtn" type="button" title="Toggle light/dark mode"></button></header><div class="messages" id="messages">6 unmodified lines</div><form class="input-bar" id="chatForm" autocomplete="off"><button type="button" class="btn-mic" id="micBtn" aria-label="Voice input" title="Ask by voice">🎤</button><textareaid="questionInput"class="question-input"9 unmodified lines</div><!-- ββ PDF reference preview modal ββ --><div class="pdf-modal hidden" id="pdfModal"><div class="pdf-modal-backdrop" id="pdfModalBackdrop"></div><div class="pdf-modal-panel"><header class="pdf-toolbar"><span class="pdf-title" id="pdfTitle">document.pdf</span><div class="pdf-nav"><button class="pdf-btn" id="pdfPrev" type="button" title="Previous page">‹</button><span class="pdf-page-label" id="pdfPageLabel">–</span><button class="pdf-btn" id="pdfNext" type="button" title="Next page">›</button></div><div class="pdf-actions"><a class="pdf-btn" id="pdfOpenTab" target="_blank" rel="noopener" title="Open PDF in new tab">↗</a><button class="pdf-btn" id="pdfClose" type="button" title="Close preview">✕</button></div></header><div class="pdf-body" id="pdfBody"><div class="pdf-canvas-wrap" id="pdfCanvasWrap"><canvas id="pdfCanvas"></canvas><div class="pdf-highlight-layer" id="pdfHighlightLayer"></div></div><div class="pdf-loading hidden" id="pdfLoading"><span class="boot-spinner"></span></div></div></div></div><script src="/static/script.js?v=14"></script></body></html>
5 unmodified lines6789101112131415161718192013 unmodified lines3435363738392 unmodified lines42434445464748495051525354555657585960616225 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391 unmodified line14114214314414514614714814915015115215315415515615715815916016116216316416516621 unmodified lines1881891901911921931 unmodified line1951961971981992002012022032042052062072082092102112122132142152162172185 unmodified lines2242252262272282291 unmodified line2312322332342352361 unmodified line2382392402412422432442452467 unmodified lines2542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842 unmodified lines28728828929029129218 unmodified lines31131231331431531654 unmodified lines37137237337437537637737837938038138238338438538638738838923 unmodified lines41341441541641741841914 unmodified lines4344354364374384398 unmodified lines4484494504514524534544553 unmodified lines4594604614624634647 unmodified lines4724734744754764774784794804815 unmodified lines/* ββ DOM refs ββ */const authOverlay = document.getElementById('authOverlay');const appShell = document.getElementById('appShell');const tabLogin = document.getElementById('tabLogin');const tabSignup = document.getElementById('tabSignup');const authForm = document.getElementById('authForm');const authEmail = document.getElementById('authEmail');const authPassword = document.getElementById('authPassword');const authSubmit = document.getElementById('authSubmit');const authSubmitText= document.getElementById('authSubmitText');const authSpinner = document.getElementById('authSpinner');const authMessage = document.getElementById('authMessage');const bootLoader = document.getElementById('bootLoader');const accountEmail = document.getElementById('accountEmail');13 unmodified linesconst sendIcon = document.getElementById('sendIcon');const sendSpinner = document.getElementById('sendSpinner');const dropZone = document.getElementById('dropZone');const fileInput = document.getElementById('fileInput');const uploadBtn = document.getElementById('uploadBtn');2 unmodified linesconst uploadStatus = document.getElementById('uploadStatus');const docList = document.getElementById('docList');const WELCOME_HTML = `<div class="message assistant welcome"><div class="bubble">Hello! Upload your policy PDFs in the sidebar, then ask me any question about them.I will only answer from the documents β no guessing.</div></div>`;/* ββ Helpers ββ */function scrollToBottom() { messagesEl.scrollTop = messagesEl.scrollHeight; }function setUISending(busy) {sendBtn.disabled = busy;sendIcon.classList.toggle('hidden', busy);sendSpinner.classList.toggle('hidden', !busy);questionInput.disabled = busy;}25 unmodified lines}/* ββ Render messages ββ */function appendMessage(role, text, sources = []) {const row = document.createElement('div');row.className = `message ${role}`;const bubble = document.createElement('div');bubble.className = 'bubble';bubble.textContent = text;row.appendChild(bubble);if (sources && sources.length > 0) {const sourcesEl = document.createElement('div');sourcesEl.className = 'sources';sources.forEach(s => {const tag = document.createElement('span');tag.className = 'source-tag';tag.innerHTML = `<strong>${escapeHTML(s.file)}</strong> p.${s.page}`;sourcesEl.appendChild(tag);});row.appendChild(sourcesEl);const allImages = sources.flatMap(s => s.image_urls || []);const uniqueImages = [...new Set(allImages)];if (uniqueImages.length > 0) {const imgLabel = document.createElement('p');imgLabel.className = 'ref-img-label';imgLabel.textContent = 'Reference images from documents:';row.appendChild(imgLabel);const imgGrid = document.createElement('div');imgGrid.className = 'ref-img-grid';uniqueImages.forEach(url => {const wrapper = document.createElement('div');wrapper.className = 'ref-img-wrapper';const img = document.createElement('img');img.src = url;img.className = 'ref-img';img.alt = 'Document reference image';img.loading = 'lazy';img.addEventListener('click', () => window.open(url, '_blank'));wrapper.appendChild(img);imgGrid.appendChild(wrapper);});row.appendChild(imgGrid);}}messagesEl.appendChild(row);1 unmodified linereturn row;}function appendTypingIndicator() {const row = document.createElement('div');row.className = 'message assistant';row.id = 'typingIndicator';const bubble = document.createElement('div');bubble.className = 'bubble typing-dots';bubble.innerHTML = '<span></span><span></span><span></span>';row.appendChild(bubble);messagesEl.appendChild(row);scrollToBottom();return row;}function removeTypingIndicator() {const el = document.getElementById('typingIndicator');if (el) el.remove();}function resetMessages() {messagesEl.innerHTML = WELCOME_HTML;}/* ββ Sessions ββ */21 unmodified linestitleSpan.textContent = s.title || 'New chat';titleSpan.addEventListener('click', () => openSession(s.id, s.title));const del = document.createElement('button');del.className = 'session-del';del.innerHTML = '×';1 unmodified linedel.addEventListener('click', (e) => { e.stopPropagation(); deleteSession(s.id); });li.appendChild(titleSpan);li.appendChild(del);sessionList.appendChild(li);});}async function openSession(sessionId, title) {currentSessionId = sessionId;chatTitle.textContent = title || 'Conversation';closeSidebar();resetMessages();try {const res = await authedFetch(`/sessions/${sessionId}/messages`);const data = await res.json();const msgs = data.messages || [];if (msgs.length > 0) messagesEl.innerHTML = '';msgs.forEach(m => appendMessage(m.role, m.content, m.sources || []));} catch { /* ignore */ }highlightActiveSession();}function highlightActiveSession() {5 unmodified linesfunction startNewChat() {currentSessionId = null;chatTitle.textContent = 'New chat';closeSidebar();resetMessages();highlightActiveSession();1 unmodified line}async function deleteSession(sessionId) {try {await authedFetch(`/sessions/${sessionId}`, { method: 'DELETE' });if (sessionId === currentSessionId) startNewChat();1 unmodified line} catch { /* ignore */ }}/* ββ Chat submit ββ */chatForm.addEventListener('submit', async (e) => {e.preventDefault();const question = questionInput.value.trim();if (!question) return;7 unmodified linessetUISending(true);appendTypingIndicator();try {const res = await authedFetch('/chat', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ question, session_id: currentSessionId }),});removeTypingIndicator();if (!res.ok) {const err = await res.json().catch(() => ({ detail: res.statusText }));appendMessage('assistant', `Error: ${err.detail || 'Something went wrong.'}`);} else {const data = await res.json();const isNew = !currentSessionId;currentSessionId = data.session_id;chatTitle.textContent = data.title || 'Conversation';appendMessage('assistant', data.answer, data.sources || []);if (isNew) await loadSessions();highlightActiveSession();}} catch (err) {removeTypingIndicator();appendMessage('assistant', err.message || 'Network error. Is the server running?');} finally {setUISending(false);questionInput.focus();}2 unmodified linesquestionInput.addEventListener('input', () => {questionInput.style.height = 'auto';questionInput.style.height = Math.min(questionInput.scrollHeight, 140) + 'px';});questionInput.addEventListener('keydown', (e) => {18 unmodified linesmenuBtn.addEventListener('click', openSidebar);sidebarBackdrop.addEventListener('click', closeSidebar);/* ββ File selection / upload ββ */fileInput.addEventListener('change', () => {uploadBtn.disabled = fileInput.files.length === 0;54 unmodified lines} else {docs.forEach(name => {const li = document.createElement('li');li.textContent = name;docList.appendChild(li);});}} catch { /* ignore */ }}/* ββ Auth UI ββ */function setAuthMode(mode) {authMode = mode;tabLogin.classList.toggle('active', mode === 'login');tabSignup.classList.toggle('active', mode === 'signup');authSubmitText.textContent = mode === 'login' ? 'Log in' : 'Create account';hideAuthMessage();}23 unmodified lineshideAuthMessage();try {if (authMode === 'signup') {const { data, error } = await sb.auth.signUp({ email, password });if (error) { showAuthMessage(error.message); return; }if (data.session) {14 unmodified lines}});async function handleSignOut() {if (sb) await sb.auth.signOut();currentSessionId = null;8 unmodified linesaccountEmail.textContent = data.user.email || 'Signed in';authOverlay.classList.add('hidden');appShell.classList.remove('hidden');startNewChat();await Promise.all([loadSessions(), loadDocumentList()]);}/* ββ Boot ββ */3 unmodified lines}async function boot() {try {if (!window.supabase || !window.supabase.createClient) {showAuthScreen();7 unmodified linesshowAuthMessage('Server is missing Supabase configuration. Check the .env file.', 'error');return;}sb = window.supabase.createClient(cfg.supabaseUrl, cfg.supabaseAnonKey);const { data } = await sb.auth.getSession();if (data.session) {await enterApp();} else {showAuthScreen();5 unmodified lines678910111213141516171819202122232425262713 unmodified lines414243444546472 unmodified lines505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313425 unmodified lines1601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662671 unmodified line26927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249321 unmodified lines5155165175185195205215225235245255261 unmodified line5285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665 unmodified lines5725735745755765775781 unmodified line5805815825835845855861 unmodified line5885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456467 unmodified lines6546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807812 unmodified lines78478578678778878979079118 unmodified lines81081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988054 unmodified lines93593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100823 unmodified lines1032103310341035103610371038103910401041104210431044104510461047104810491050105114 unmodified lines1066106710681069107010711072107310748 unmodified lines1083108410851086108710881089109010911092109310941095109610971098109911001101110211033 unmodified lines110711081109111011111112111311141115111611171118111911201121112211231124112511267 unmodified lines1134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911605 unmodified lines/* ββ DOM refs ββ */const authOverlay = document.getElementById('authOverlay');const appShell = document.getElementById('appShell');const authTabs = document.getElementById('authTabs');const tabLogin = document.getElementById('tabLogin');const tabSignup = document.getElementById('tabSignup');const authForm = document.getElementById('authForm');const authEmail = document.getElementById('authEmail');const authEmailLabel = document.getElementById('authEmailLabel');const authPassword = document.getElementById('authPassword');const authPasswordLabel = document.getElementById('authPasswordLabel');const passwordWrap = document.getElementById('passwordWrap');const togglePw = document.getElementById('togglePw');const authSubmit = document.getElementById('authSubmit');const authSubmitText= document.getElementById('authSubmitText');const authSpinner = document.getElementById('authSpinner');const authMessage = document.getElementById('authMessage');const forgotBtn = document.getElementById('forgotBtn');const backToLogin = document.getElementById('backToLogin');const bootLoader = document.getElementById('bootLoader');const accountEmail = document.getElementById('accountEmail');13 unmodified linesconst sendIcon = document.getElementById('sendIcon');const sendSpinner = document.getElementById('sendSpinner');const uploadPanel = document.getElementById('uploadPanel');const dropZone = document.getElementById('dropZone');const fileInput = document.getElementById('fileInput');const uploadBtn = document.getElementById('uploadBtn');2 unmodified linesconst uploadStatus = document.getElementById('uploadStatus');const docList = document.getElementById('docList');const micBtn = document.getElementById('micBtn');const exportBtn = document.getElementById('exportBtn');const analyticsBtn = document.getElementById('analyticsBtn');const themeBtn = document.getElementById('themeBtn');const themeBtnAuth = document.getElementById('themeBtnAuth');/* ββ Theme (light/dark) ββ */const ICON_SUN = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>`;const ICON_MOON = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>`;function applyTheme(theme) {document.documentElement.dataset.theme = theme;localStorage.setItem('docent-theme', theme);const icon = theme === 'light' ? ICON_MOON : ICON_SUN;themeBtn.innerHTML = icon;themeBtnAuth.innerHTML = icon;}function toggleTheme() {applyTheme(document.documentElement.dataset.theme === 'light' ? 'dark' : 'light');}themeBtn.addEventListener('click', toggleTheme);themeBtnAuth.addEventListener('click', toggleTheme);applyTheme(localStorage.getItem('docent-theme') || 'dark');/* ββ Password show/hide eye ββ */const ICON_EYE = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>`;const ICON_EYE_OFF = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>`;togglePw.innerHTML = ICON_EYE;togglePw.addEventListener('click', () => {const show = authPassword.type === 'password';authPassword.type = show ? 'text' : 'password';togglePw.innerHTML = show ? ICON_EYE_OFF : ICON_EYE;togglePw.title = show ? 'Hide password' : 'Show password';authPassword.focus();});let isAdmin = false;const STARTER_QUESTIONS = ['What is the plagiarism policy?','What are the admission requirements?','What is the attendance policy for online classes?','How can I transfer credit hours from another university?',];function welcomeHTML() {const intro = isAdmin? 'Hello! Upload your policy PDFs in the sidebar, then ask me any question about them.': 'Hello! Ask me any question about the policy documents.';const chips = STARTER_QUESTIONS.map(q => `<button type="button" class="starter-chip">${escapeHTML(q)}</button>`).join('');return `<div class="message assistant welcome"><div class="bubble">${intro}I will only answer from the documents β no guessing.</div><div class="starter-chips">${chips}</div></div>`;}/* ββ Helpers ββ */function scrollToBottom() { messagesEl.scrollTop = messagesEl.scrollHeight; }let isStreaming = false;let chatAbort = null;function setUISending(busy) {isStreaming = busy;// While streaming, the send button becomes a stop buttonsendIcon.innerHTML = busy ? '■' : '►';sendBtn.title = busy ? 'Stop generating' : 'Send';sendBtn.classList.toggle('stopping', busy);sendIcon.classList.remove('hidden');sendSpinner.classList.add('hidden');questionInput.disabled = busy;}25 unmodified lines}/* ββ Render messages ββ */if (window.marked) marked.setOptions({ breaks: true, gfm: true });/* Assistant answers are markdown (lists, boldβ¦); render them safely.User messages stay plain text. */function setBubbleContent(bubble, role, text) {if (role === 'assistant' && window.marked && window.DOMPurify) {bubble.classList.add('md');bubble.innerHTML = DOMPurify.sanitize(marked.parse(text || ''));} else {bubble.textContent = text;}}function renderSources(row, sources) {if (!sources || sources.length === 0) return;const sourcesEl = document.createElement('div');sourcesEl.className = 'sources';sources.forEach(s => {const page = sourceDisplayPage(s);const tag = document.createElement('button');tag.type = 'button';tag.className = 'source-tag';tag.title = 'Preview this page of the PDF';tag.innerHTML = `<strong>${escapeHTML(s.file)}</strong> p.${page} <span class="source-view">🔍</span>`;tag.addEventListener('click', () => openPdfPreview(s.file, page, s.snippets || []));sourcesEl.appendChild(tag);});row.appendChild(sourcesEl);const allImages = sources.flatMap(s => s.image_urls || []);const uniqueImages = [...new Set(allImages)];if (uniqueImages.length > 0) {const imgLabel = document.createElement('p');imgLabel.className = 'ref-img-label';imgLabel.textContent = 'Reference images from documents:';row.appendChild(imgLabel);const imgGrid = document.createElement('div');imgGrid.className = 'ref-img-grid';uniqueImages.forEach(url => {const wrapper = document.createElement('div');wrapper.className = 'ref-img-wrapper';const img = document.createElement('img');img.src = url;img.className = 'ref-img';img.alt = 'Document reference image';img.loading = 'lazy';img.addEventListener('click', () => window.open(url, '_blank'));wrapper.appendChild(img);imgGrid.appendChild(wrapper);});row.appendChild(imgGrid);}}/* π/π buttons under an assistant answer; state is stored in Supabase */function addFeedbackBar(row, messageId, current) {if (!messageId || row.querySelector('.feedback-bar')) return;const bar = document.createElement('div');bar.className = 'feedback-bar';const make = (value, icon, label) => {const btn = document.createElement('button');btn.type = 'button';btn.className = 'fb-btn' + (current === value ? ' active' : '');btn.innerHTML = icon;btn.title = label;btn.addEventListener('click', async () => {const newValue = btn.classList.contains('active') ? null : value;try {await authedFetch(`/messages/${messageId}/feedback`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ value: newValue }),});bar.querySelectorAll('.fb-btn').forEach(b => b.classList.remove('active'));if (newValue) btn.classList.add('active');} catch { /* ignore */ }});return btn;};bar.appendChild(make('up', '👍', 'Helpful'));bar.appendChild(make('down', '👎', 'Not helpful'));row.appendChild(bar);}function appendMessage(role, text, sources = [], info = null) {const row = document.createElement('div');row.className = `message ${role}`;const bubble = document.createElement('div');bubble.className = 'bubble';setBubbleContent(bubble, role, text);row.appendChild(bubble);renderSources(row, sources);if (role === 'assistant' && info && info.id) {addFeedbackBar(row, info.id, info.feedback || null);}messagesEl.appendChild(row);1 unmodified linereturn row;}/* ββ PDF reference preview ββ */const pdfModal = document.getElementById('pdfModal');const pdfModalBackdrop = document.getElementById('pdfModalBackdrop');const pdfTitle = document.getElementById('pdfTitle');const pdfPrev = document.getElementById('pdfPrev');const pdfNext = document.getElementById('pdfNext');const pdfPageLabel = document.getElementById('pdfPageLabel');const pdfOpenTab = document.getElementById('pdfOpenTab');const pdfCloseBtn = document.getElementById('pdfClose');const pdfBody = document.getElementById('pdfBody');const pdfCanvas = document.getElementById('pdfCanvas');const pdfHighlightLayer = document.getElementById('pdfHighlightLayer');const pdfLoading = document.getElementById('pdfLoading');if (window.pdfjsLib) {pdfjsLib.GlobalWorkerOptions.workerSrc ='https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.worker.min.js';}let pdfDoc = null;let pdfCurrentUrl = '';let pdfPageNum = 1;let pdfSnippets = [];let pdfRenderTask = null;let pdfRenderSeq = 0;/* Older stored messages have 0-based pages and no snippets; new ones are1-based and carry the retrieved chunk text. */function sourceDisplayPage(s) {const n = Number(s.page);if (!Number.isFinite(n)) return 1;return Array.isArray(s.snippets) ? Math.max(1, n) : n + 1;}async function openPdfPreview(file, page, snippets) {const url = `/docs/${encodeURIComponent(file)}`;if (!window.pdfjsLib) {// Fallback: the browser's own viewer still jumps to the pagewindow.open(`${url}#page=${page}`, '_blank');return;}pdfTitle.textContent = file;pdfSnippets = snippets || [];pdfHighlightLayer.innerHTML = '';pdfPageLabel.textContent = 'β¦';pdfModal.classList.remove('hidden');pdfLoading.classList.remove('hidden');try {if (!pdfDoc || pdfCurrentUrl !== url) {pdfDoc = await pdfjsLib.getDocument(url).promise;pdfCurrentUrl = url;}pdfPageNum = Math.min(Math.max(1, page || 1), pdfDoc.numPages);await renderPdfPage();} catch (err) {pdfPageLabel.textContent = 'failed to load';pdfDoc = null;pdfCurrentUrl = '';} finally {pdfLoading.classList.add('hidden');}}async function renderPdfPage() {if (!pdfDoc) return;const seq = ++pdfRenderSeq;pdfPageLabel.textContent = `${pdfPageNum} / ${pdfDoc.numPages}`;pdfOpenTab.href = `${pdfCurrentUrl}#page=${pdfPageNum}`;pdfPrev.disabled = pdfPageNum <= 1;pdfNext.disabled = pdfPageNum >= pdfDoc.numPages;const page = await pdfDoc.getPage(pdfPageNum);if (seq !== pdfRenderSeq) return;// Fit the page to the modal width (capped so text stays readable)const base = page.getViewport({ scale: 1 });const available = Math.max(pdfBody.clientWidth - 36, 280);const scale = Math.min(Math.max(available / base.width, 0.5), 2.5);const viewport = page.getViewport({ scale });const dpr = window.devicePixelRatio || 1;pdfCanvas.width = Math.floor(viewport.width * dpr);pdfCanvas.height = Math.floor(viewport.height * dpr);pdfCanvas.style.width = `${Math.floor(viewport.width)}px`;pdfCanvas.style.height = `${Math.floor(viewport.height)}px`;pdfHighlightLayer.innerHTML = '';if (pdfRenderTask) { try { pdfRenderTask.cancel(); } catch { /* ignore */ } }pdfRenderTask = page.render({canvasContext: pdfCanvas.getContext('2d'),viewport,transform: dpr !== 1 ? [dpr, 0, 0, dpr, 0, 0] : null,});try {await pdfRenderTask.promise;} catch (err) {return; // cancelled by a newer render}if (seq !== pdfRenderSeq) return;await drawPdfHighlights(page, viewport);}/* Highlight the text items on the page that belong to the retrieved chunks. */async function drawPdfHighlights(page, viewport) {const norm = t => t.toLowerCase().replace(/\s+/g, ' ').trim();const snips = (pdfSnippets || []).map(norm).filter(s => s.length > 0);if (snips.length === 0) return;const snippetWords = new Set(snips.join(' ').split(' ').filter(w => w.length >= 4));const textContent = await page.getTextContent();let firstHighlight = null;for (const item of textContent.items) {const t = norm(item.str || '');if (t.length < 4) continue;// Exact containment first; fall back to word overlap because PDF.js and// pypdf extract whitespace slightly differently.let match = snips.some(s => s.includes(t));if (!match) {const words = t.split(' ').filter(w => w.length >= 4);if (words.length >= 2) {const hits = words.filter(w => snippetWords.has(w)).length;match = hits / words.length >= 0.6;}}if (!match) continue;const tx = pdfjsLib.Util.transform(viewport.transform, item.transform);const fontH = Math.hypot(tx[2], tx[3]);const hl = document.createElement('div');hl.className = 'pdf-highlight';hl.style.left = `${tx[4]}px`;hl.style.top = `${tx[5] - fontH}px`;hl.style.width = `${(item.width || 0) * viewport.scale}px`;hl.style.height = `${fontH * 1.2}px`;pdfHighlightLayer.appendChild(hl);if (!firstHighlight) firstHighlight = hl;}if (firstHighlight) {firstHighlight.scrollIntoView({ block: 'center', behavior: 'smooth' });}}function closePdfModal() {pdfModal.classList.add('hidden');}pdfPrev.addEventListener('click', () => {if (pdfDoc && pdfPageNum > 1) { pdfPageNum--; renderPdfPage(); }});pdfNext.addEventListener('click', () => {if (pdfDoc && pdfPageNum < pdfDoc.numPages) { pdfPageNum++; renderPdfPage(); }});pdfCloseBtn.addEventListener('click', closePdfModal);pdfModalBackdrop.addEventListener('click', closePdfModal);document.addEventListener('keydown', (e) => {if (pdfModal.classList.contains('hidden')) return;if (e.key === 'Escape') closePdfModal();if (e.key === 'ArrowLeft') pdfPrev.click();if (e.key === 'ArrowRight') pdfNext.click();});let typingTicker = null;function appendTypingIndicator() {removeTypingIndicator();const row = document.createElement('div');row.className = 'message assistant';row.id = 'typingIndicator';const bubble = document.createElement('div');bubble.className = 'bubble typing-bubble';bubble.innerHTML = `<span class="typing-dots"><span></span><span></span><span></span></span><span class="typing-status" id="typingStatus">Searching policy documentsβ¦</span><span class="typing-timer" id="typingTimer"></span>`;row.appendChild(bubble);messagesEl.appendChild(row);scrollToBottom();// Show elapsed time and reassure the user during long waits β the free// NVIDIA endpoint can queue requests when it's busy.const start = Date.now();typingTicker = setInterval(() => {const timer = document.getElementById('typingTimer');const status = document.getElementById('typingStatus');if (!timer || !status) return;const secs = Math.round((Date.now() - start) / 1000);if (secs >= 3) timer.textContent = `${secs}s`;if (secs >= 45) {status.textContent = 'Still queued β the free AI service is crowded. Press β to cancel if needed.';} else if (secs >= 15) {status.textContent = 'The AI service is a bit busy β still working on itβ¦';}}, 1000);return row;}function setTypingStatus(text) {const status = document.getElementById('typingStatus');if (status) status.textContent = text;}function removeTypingIndicator() {if (typingTicker) { clearInterval(typingTicker); typingTicker = null; }const el = document.getElementById('typingIndicator');if (el) el.remove();}function resetMessages() {messagesEl.innerHTML = welcomeHTML();}/* ββ Sessions ββ */21 unmodified linestitleSpan.textContent = s.title || 'New chat';titleSpan.addEventListener('click', () => openSession(s.id, s.title));const ren = document.createElement('button');ren.className = 'session-ren';ren.innerHTML = '✎';ren.title = 'Rename conversation';ren.addEventListener('click', (e) => { e.stopPropagation(); startRename(li, s); });const del = document.createElement('button');del.className = 'session-del';del.innerHTML = '×';1 unmodified linedel.addEventListener('click', (e) => { e.stopPropagation(); deleteSession(s.id); });li.appendChild(titleSpan);li.appendChild(ren);li.appendChild(del);sessionList.appendChild(li);});}let openSessionSeq = 0;async function openSession(sessionId, title) {// Switch the UI immediately; the messages stream in when the API answersconst seq = ++openSessionSeq;currentSessionId = sessionId;chatTitle.textContent = title || 'Conversation';exportBtn.classList.remove('hidden');closeSidebar();highlightActiveSession();messagesEl.innerHTML = '<div class="messages-loading"><span class="boot-spinner"></span></div>';try {const res = await authedFetch(`/sessions/${sessionId}/messages`);const data = await res.json();if (seq !== openSessionSeq) return; // user already switched againconst msgs = data.messages || [];messagesEl.innerHTML = '';if (msgs.length === 0) {resetMessages();} else {msgs.forEach(m => appendMessage(m.role, m.content, m.sources || [], { id: m.id, feedback: m.feedback }));}scrollToBottom();} catch {if (seq === openSessionSeq) resetMessages();}}function highlightActiveSession() {5 unmodified linesfunction startNewChat() {currentSessionId = null;chatTitle.textContent = 'New chat';exportBtn.classList.add('hidden');closeSidebar();resetMessages();highlightActiveSession();1 unmodified line}async function deleteSession(sessionId) {if (!confirm('Delete this conversation? This cannot be undone.')) return;try {await authedFetch(`/sessions/${sessionId}`, { method: 'DELETE' });if (sessionId === currentSessionId) startNewChat();1 unmodified line} catch { /* ignore */ }}/* Inline rename: swap the title for an input; Enter/blur saves, Esc cancels */function startRename(li, s) {const titleSpan = li.querySelector('.session-title');if (!titleSpan) return;const input = document.createElement('input');input.type = 'text';input.className = 'session-rename-input';input.value = s.title || 'New chat';input.maxLength = 80;li.replaceChild(input, titleSpan);input.focus();input.select();let cancelled = false;let finished = false;const finish = async () => {if (finished) return;finished = true;const title = input.value.trim();if (!cancelled && title && title !== s.title) {try {await authedFetch(`/sessions/${s.id}`, {method: 'PATCH',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ title }),});if (s.id === currentSessionId) chatTitle.textContent = title;} catch { /* keep old title */ }}await loadSessions();};input.addEventListener('keydown', (e) => {e.stopPropagation();if (e.key === 'Enter') input.blur();else if (e.key === 'Escape') { cancelled = true; input.blur(); }});input.addEventListener('blur', finish);input.addEventListener('click', (e) => e.stopPropagation());}/* ββ Chat submit ββ */chatForm.addEventListener('submit', async (e) => {e.preventDefault();// While an answer is streaming, the send button acts as a stop buttonif (isStreaming) {if (chatAbort) chatAbort.abort();return;}const question = questionInput.value.trim();if (!question) return;7 unmodified linessetUISending(true);appendTypingIndicator();const wasNew = !currentSessionId;let row = null;let bubble = null;let meta = null;let answerText = '';let doneMsgId = null;// Typewriter buffer: the API delivers tokens in bursts, so instead of// rendering lumps we queue incoming text and reveal it at a steady rate// (speeding up when the queue grows, so we never lag behind).let pendingText = '';let typeTimer = null;const typeTick = () => {if (!pendingText) return;const step = Math.max(2, Math.ceil(pendingText.length / 25));answerText += pendingText.slice(0, step);pendingText = pendingText.slice(step);setBubbleContent(bubble, 'assistant', answerText);scrollToBottom();};const stopTypewriter = () => {if (typeTimer) { clearInterval(typeTimer); typeTimer = null; }if (pendingText && bubble) {answerText += pendingText;pendingText = '';setBubbleContent(bubble, 'assistant', answerText);}};const ensureRow = () => {if (row) return;removeTypingIndicator();row = appendMessage('assistant', '');bubble = row.querySelector('.bubble');bubble.classList.add('streaming');};const finalize = async () => {stopTypewriter();removeTypingIndicator();if (bubble) bubble.classList.remove('streaming');if (meta) {if (row) renderSources(row, meta.sources || []);if (wasNew) await loadSessions();highlightActiveSession();}if (row && doneMsgId) addFeedbackBar(row, doneMsgId, null);if (currentSessionId) exportBtn.classList.remove('hidden');scrollToBottom();};try {chatAbort = new AbortController();const res = await authedFetch('/chat', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ question, session_id: currentSessionId }),signal: chatAbort.signal,});if (!res.ok) {removeTypingIndicator();const err = await res.json().catch(() => ({ detail: res.statusText }));appendMessage('assistant', `Error: ${err.detail || 'Something went wrong.'}`);return;}// The answer arrives as a server-sent-event stream:// meta (session + sources) β delta tokens β doneconst handleEvent = (evt) => {if (evt.type === 'meta') {meta = evt;currentSessionId = evt.session_id;chatTitle.textContent = evt.title || 'Conversation';const n = (evt.sources || []).length;setTypingStatus(n > 0? `Found ${n} relevant passage${n === 1 ? '' : 's'} β writing the answerβ¦`: 'Writing the answerβ¦');} else if (evt.type === 'delta') {ensureRow();pendingText += evt.text;if (!typeTimer) typeTimer = setInterval(typeTick, 24);} else if (evt.type === 'error') {ensureRow();stopTypewriter();answerText += (answerText ? '\n\n' : '') + (evt.detail || 'Something went wrong.');setBubbleContent(bubble, 'assistant', answerText);} else if (evt.type === 'done') {doneMsgId = evt.message_id || null;}};const reader = res.body.getReader();const decoder = new TextDecoder();let buf = '';while (true) {const { done, value } = await reader.read();if (done) break;buf += decoder.decode(value, { stream: true });let sep;while ((sep = buf.indexOf('\n\n')) !== -1) {const raw = buf.slice(0, sep).trim();buf = buf.slice(sep + 2);if (!raw.startsWith('data:')) continue;try { handleEvent(JSON.parse(raw.slice(5))); } catch { /* skip bad frame */ }}}await finalize();if (!row) appendMessage('assistant', 'No answer received. Please try again.');} catch (err) {if (err.name === 'AbortError') {// User pressed stop β keep the partial answer on screenawait finalize();} else {removeTypingIndicator();appendMessage('assistant', err.message || 'Network error. Is the server running?');}} finally {chatAbort = null;setUISending(false);questionInput.focus();}2 unmodified linesquestionInput.addEventListener('input', () => {questionInput.style.height = 'auto';questionInput.style.height = Math.min(questionInput.scrollHeight, 140) + 'px';// Only show a scrollbar once the textarea has grown to its max heightquestionInput.style.overflowY = questionInput.scrollHeight > 140 ? 'auto' : 'hidden';});questionInput.addEventListener('keydown', (e) => {18 unmodified linesmenuBtn.addEventListener('click', openSidebar);sidebarBackdrop.addEventListener('click', closeSidebar);/* ββ Starter question chips (welcome screen) ββ */messagesEl.addEventListener('click', (e) => {const chip = e.target.closest('.starter-chip');if (!chip || isStreaming) return;questionInput.value = chip.textContent;chatForm.dispatchEvent(new Event('submit'));});/* ββ Voice input (browser Web Speech API β free, works in Chrome/Edge) ββ */const SpeechRec = window.SpeechRecognition || window.webkitSpeechRecognition;let recognition = null;let recActive = false;if (!SpeechRec) {micBtn.classList.add('hidden');} else {micBtn.addEventListener('click', () => {if (recActive) { recognition.stop(); return; }recognition = new SpeechRec();recognition.lang = 'en-US';recognition.interimResults = false;recognition.maxAlternatives = 1;recognition.onresult = (e) => {const transcript = e.results[0][0].transcript;questionInput.value = (questionInput.value ? questionInput.value + ' ' : '') + transcript;questionInput.dispatchEvent(new Event('input'));questionInput.focus();};recognition.onend = () => {recActive = false;micBtn.classList.remove('recording');};recActive = true;micBtn.classList.add('recording');recognition.start();});}/* ββ Export conversation as a text file ββ */exportBtn.addEventListener('click', async () => {if (!currentSessionId) return;try {const res = await authedFetch(`/sessions/${currentSessionId}/messages`);const data = await res.json();const title = chatTitle.textContent || 'Conversation';const lines = (data.messages || []).map(m => {const who = m.role === 'user' ? 'You' : 'Docent AI';const cites = (m.sources || []).map(s => ` [source: ${s.file}, p.${sourceDisplayPage(s)}]`).join('\n');return `${who}:\n${m.content}${cites ? '\n' + cites : ''}\n`;});const text = `${title}\nExported ${new Date().toLocaleString()}\n${'='.repeat(50)}\n\n${lines.join('\n')}`;const blob = new Blob([text], { type: 'text/plain' });const a = document.createElement('a');a.href = URL.createObjectURL(blob);a.download = `${title.replace(/[^\w\- ]+/g, '').trim() || 'chat'}.txt`;a.click();URL.revokeObjectURL(a.href);} catch { /* ignore */ }});/* ββ Admin analytics: full dashboard page ββ */analyticsBtn.addEventListener('click', () => { window.location.href = '/admin'; });/* ββ File selection / upload ββ */fileInput.addEventListener('change', () => {uploadBtn.disabled = fileInput.files.length === 0;54 unmodified lines} else {docs.forEach(name => {const li = document.createElement('li');li.className = 'doc-item';const span = document.createElement('span');span.className = 'doc-name';span.textContent = name;const del = document.createElement('button');del.type = 'button';del.className = 'doc-del';del.innerHTML = '×';del.title = 'Remove this document from the knowledge base';del.addEventListener('click', () => deleteDocument(name, li));li.appendChild(span);li.appendChild(del);docList.appendChild(li);});}} catch { /* ignore */ }}async function deleteDocument(name, li) {if (!confirm(`Remove "${name}" and all of its content from the knowledge base?`)) return;li.style.opacity = '.4';try {const res = await authedFetch(`/documents/${encodeURIComponent(name)}`, { method: 'DELETE' });if (!res.ok) throw new Error();const data = await res.json();uploadStatus.textContent = `Removed ${name} (${data.chunks_removed} chunks)`;uploadStatus.classList.remove('hidden');await loadDocumentList();} catch {li.style.opacity = '';uploadStatus.textContent = `Could not remove ${name}.`;uploadStatus.classList.remove('hidden');}}/* ββ Auth UI ββModes: 'login' | 'signup' | 'forgot' (request reset email)| 'recovery' (arrived via the reset link β set a new password) */function setAuthMode(mode) {authMode = mode;const showEmail = mode !== 'recovery';const showPassword = mode === 'login' || mode === 'signup' || mode === 'recovery';const showTabs = mode === 'login' || mode === 'signup';authTabs.classList.toggle('hidden', !showTabs);authEmail.classList.toggle('hidden', !showEmail);authEmailLabel.classList.toggle('hidden', !showEmail);passwordWrap.classList.toggle('hidden', !showPassword);authPasswordLabel.classList.toggle('hidden', !showPassword);authEmail.required = showEmail;authPassword.required = showPassword;forgotBtn.classList.toggle('hidden', mode !== 'login');backToLogin.classList.toggle('hidden', mode !== 'forgot');authPasswordLabel.textContent = mode === 'recovery' ? 'New password' : 'Password';tabLogin.classList.toggle('active', mode === 'login');tabSignup.classList.toggle('active', mode === 'signup');authSubmitText.textContent = {login: 'Log in',signup: 'Create account',forgot: 'Send reset link',recovery: 'Set new password',}[mode];hideAuthMessage();}23 unmodified lineshideAuthMessage();try {if (authMode === 'recovery') {const { error } = await sb.auth.updateUser({ password });if (error) { showAuthMessage(error.message); return; }// Remove the recovery tokens from the URL before entering the apphistory.replaceState(null, '', window.location.pathname);setAuthMode('login');await enterApp();} else if (authMode === 'forgot') {const { error } = await sb.auth.resetPasswordForEmail(email, {redirectTo: window.location.origin,});if (error) { showAuthMessage(error.message); return; }showAuthMessage('Reset link sent β check your inbox, then follow the link to set a new password.', 'success');} else if (authMode === 'signup') {const { data, error } = await sb.auth.signUp({ email, password });if (error) { showAuthMessage(error.message); return; }if (data.session) {14 unmodified lines}});forgotBtn.addEventListener('click', () => setAuthMode('forgot'));backToLogin.addEventListener('click', () => setAuthMode('login'));async function handleSignOut() {if (sb) await sb.auth.signOut();currentSessionId = null;8 unmodified linesaccountEmail.textContent = data.user.email || 'Signed in';authOverlay.classList.add('hidden');appShell.classList.remove('hidden');// Only admins get the document-upload panelisAdmin = false;try {const res = await authedFetch('/me');const me = await res.json();isAdmin = !!me.is_admin;} catch { /* treat as regular user */ }uploadPanel.classList.toggle('hidden', !isAdmin);analyticsBtn.classList.toggle('hidden', !isAdmin);startNewChat();const tasks = [loadSessions()];if (isAdmin) tasks.push(loadDocumentList());await Promise.all(tasks);}/* ββ Boot ββ */3 unmodified lines}async function boot() {// A stale service worker from another app previously hosted on this origin// (localhost:8000) intercepts all requests and buffers streamed responses.// Remove any and reload once so fetches go direct again.if ('serviceWorker' in navigator) {try {const regs = await navigator.serviceWorker.getRegistrations();if (regs.length > 0) {await Promise.all(regs.map(r => r.unregister()));window.location.reload();return;}} catch { /* not critical */ }}try {if (!window.supabase || !window.supabase.createClient) {showAuthScreen();7 unmodified linesshowAuthMessage('Server is missing Supabase configuration. Check the .env file.', 'error');return;}// A password-reset link lands here with recovery tokens in the URL hash.// Detect it BEFORE checking the session β the link logs the user in, and// we must show the "set new password" form instead of the app.const isRecoveryLink = window.location.hash.includes('type=recovery');sb = window.supabase.createClient(cfg.supabaseUrl, cfg.supabaseAnonKey);sb.auth.onAuthStateChange((event) => {if (event === 'PASSWORD_RECOVERY') {showAuthScreen();setAuthMode('recovery');showAuthMessage('Enter a new password for your account.', 'success');}});const { data } = await sb.auth.getSession();if (isRecoveryLink) {showAuthScreen();setAuthMode('recovery');showAuthMessage('Enter a new password for your account.', 'success');} else if (data.session) {await enterApp();} else {showAuthScreen();
1 unmodified line2345675 unmodified lines131415161718192021222324168 unmodified lines19319419519619719819920020120220320419 unmodified lines22422522622722822911 unmodified lines24124224324424524624724824925025125225325425525632 unmodified lines28929029129229329429519 unmodified lines31531631731831932031 unmodified lines35235335435535635714 unmodified lines37237337437537637737899 unmodified lines47847948048148248348448538 unmodified lines5245255265275285295305314 unmodified lines5365375385395405415424 unmodified lines54754854955055155255355465 unmodified lines6206216226236246256261 unmodified line*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }:root {--bg: #0f1117;--surface: #1a1d27;--surface2: #22263a;5 unmodified lines--user-bg: #1e3a5f;--user-text: #cce4ff;--ai-bg: #1e2235;--radius: 12px;--font: 'Segoe UI', system-ui, sans-serif;}html, body { height: 100%; overflow: hidden; }body { font-family: var(--font); background: var(--bg); color: var(--text); }/* ββ Layout ββ */.app-shell {168 unmodified linesscroll-behavior: smooth;}.messages::-webkit-scrollbar { width: 6px; }.messages::-webkit-scrollbar-track { background: transparent; }.messages::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }/* Message rows */.message { display: flex; flex-direction: column; max-width: 78%; }.message.user { align-self: flex-end; align-items: flex-end; }.message.assistant { align-self: flex-start; align-items: flex-start; }19 unmodified linesborder: 1px solid var(--border);}.message.welcome .bubble {background: transparent;border: 1px dashed var(--border);11 unmodified lines.source-tag {font-size: .72rem;padding: 3px 9px;border-radius: 20px;background: var(--surface2);border: 1px solid var(--border);color: var(--text-muted);}.source-tag strong { color: var(--accent); }/* Typing indicator */.typing-dots span {display: inline-block;width: 7px; height: 7px;32 unmodified linesline-height: 1.5;padding: 11px 14px;max-height: 140px;overflow-y: auto;transition: border-color .2s;}19 unmodified lines.btn-send:hover:not(:disabled) { background: var(--accent-dk); }.btn-send:active:not(:disabled){ transform: scale(.93); }.btn-send:disabled { opacity: .45; cursor: not-allowed; }/* ββ Reference images ββ */.ref-img-label {31 unmodified lines.ref-img:hover { opacity: .85; }/* ββ Utility ββ */.hidden { display: none !important; }14 unmodified linesdisplay: flex;align-items: center;justify-content: center;background: radial-gradient(circle at 30% 20%, #16202b, var(--bg));z-index: 50;padding: 20px;}99 unmodified linesborder-radius: 8px;line-height: 1.5;}.auth-message.error { background: rgba(220,70,70,.12); color: #ff9c9c; border: 1px solid rgba(220,70,70,.3); }.auth-message.success { background: rgba(118,185,0,.12); color: #b6e26a; border: 1px solid rgba(118,185,0,.3); }/* ββ New chat button ββ */.btn-new-chat {38 unmodified linesborder-left: 3px solid transparent;transition: border-color .15s, background .15s;}.session-item:hover { background: #272c43; }.session-item.active { border-left-color: var(--accent); background: #272c43; }.session-title {flex: 1;4 unmodified linestext-overflow: ellipsis;}.session-del {background: none;border: none;color: var(--text-muted);4 unmodified linesopacity: 0;transition: opacity .15s, color .15s;}.session-item:hover .session-del { opacity: 1; }.session-del:hover { color: #ff9c9c; }.session-empty {color: var(--text-muted);65 unmodified linesalign-items: center;gap: 12px;}.chat-header-text { min-width: 0; }.menu-btn {display: none;1 unmodified line23456785 unmodified lines14151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768168 unmodified lines23723823924024124224324424524624724824925025125225325425525625725825926026126219 unmodified lines28228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632711 unmodified lines33934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539632 unmodified lines42943043143243343443519 unmodified lines45545645745845946046146231 unmodified lines49449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286314 unmodified lines87887988088188288388499 unmodified lines98498598698798898999099138 unmodified lines103010311032103310341035103610374 unmodified lines104210431044104510461047104810494 unmodified lines10541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107765 unmodified lines11431144114511461147114811491 unmodified line*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }:root {color-scheme: dark;--bg: #0f1117;--surface: #1a1d27;--surface2: #22263a;5 unmodified lines--user-bg: #1e3a5f;--user-text: #cce4ff;--ai-bg: #1e2235;--hover: #272c43;--code-bg: #12141d;--pdf-bg: #0a0c12;--strong: #ffffff;--scroll-thumb: #2e3350;--auth-glow: #16202b;--err-text: #ff9c9c;--ok-text: #b6e26a;--radius: 12px;--font: 'Segoe UI', system-ui, sans-serif;}[data-theme="light"] {color-scheme: light;--bg: #eef1f6;--surface: #ffffff;--surface2: #f1f3f8;--border: #d7dce6;--accent: #6aa800;--accent-dk: #578a00;--text: #1c2130;--text-muted:#68708a;--user-bg: #dbeafe;--user-text: #1e3a5f;--ai-bg: #ffffff;--hover: #e5e9f2;--code-bg: #eef1f6;--pdf-bg: #d9dee7;--strong: #000000;--scroll-thumb: #c3cad8;--auth-glow: #dfeaf7;--err-text: #b02a2a;--ok-text: #3f7d00;}html, body { height: 100%; overflow: hidden; }body {font-family: var(--font);background: var(--bg);color: var(--text);transition: background-color .25s, color .25s;}/* ββ Themed scrollbars (everywhere) ββ */* { scrollbar-width: thin; scrollbar-color: var(--scroll-thumb) transparent; }::-webkit-scrollbar { width: 8px; height: 8px; }::-webkit-scrollbar-track { background: transparent; }::-webkit-scrollbar-thumb { background: var(--scroll-thumb); border-radius: 4px; }::-webkit-scrollbar-thumb:hover { background: var(--accent); }/* ββ Layout ββ */.app-shell {168 unmodified linesscroll-behavior: smooth;}/* Loader shown while a conversation's messages are fetched */.messages-loading {display: flex;align-items: center;justify-content: center;padding: 60px 0;}/* Message rows */.message {display: flex;flex-direction: column;max-width: 78%;animation: msg-in .2s ease;}@keyframes msg-in {from { opacity: 0; transform: translateY(6px); }to { opacity: 1; transform: none; }}.message.user { align-self: flex-end; align-items: flex-end; }.message.assistant { align-self: flex-start; align-items: flex-start; }19 unmodified linesborder: 1px solid var(--border);}/* Markdown-rendered assistant answers */.bubble.md { white-space: normal; }.bubble.md p, .bubble.md ul, .bubble.md ol,.bubble.md pre, .bubble.md table, .bubble.md blockquote { margin: 0 0 10px; }.bubble.md > :last-child { margin-bottom: 0; }.bubble.md ul, .bubble.md ol { padding-left: 20px; }.bubble.md li { margin: 3px 0; }.bubble.md h1, .bubble.md h2, .bubble.md h3, .bubble.md h4 {font-size: 1em;margin: 12px 0 6px;}.bubble.md code {background: var(--code-bg);border: 1px solid var(--border);padding: 1px 5px;border-radius: 4px;font-size: .85em;}.bubble.md pre {background: var(--code-bg);border: 1px solid var(--border);padding: 10px 12px;border-radius: 8px;overflow-x: auto;}.bubble.md pre code { background: none; padding: 0; }.bubble.md table { border-collapse: collapse; display: block; overflow-x: auto; }.bubble.md th, .bubble.md td {border: 1px solid var(--border);padding: 4px 8px;font-size: .85em;}.bubble.md strong { color: var(--strong); }.bubble.md a { color: var(--accent); }.bubble.md blockquote {border-left: 3px solid var(--accent);padding-left: 10px;color: var(--text-muted);}.message.welcome .bubble {background: transparent;border: 1px dashed var(--border);11 unmodified lines.source-tag {font-size: .72rem;font-family: var(--font);padding: 3px 9px;border-radius: 20px;background: var(--surface2);border: 1px solid var(--border);color: var(--text-muted);cursor: pointer;transition: border-color .15s, background .15s;}.source-tag:hover {border-color: var(--accent);background: rgba(118, 185, 0, .08);color: var(--text);}.source-tag strong { color: var(--accent); }.source-view { font-size: .68rem; }/* Typing indicator */.typing-bubble {display: flex;align-items: center;gap: 10px;max-width: 100%;}.typing-dots { flex-shrink: 0; }.typing-status {font-size: .8rem;color: var(--text-muted);font-style: italic;}.typing-timer {font-size: .72rem;color: var(--text-muted);opacity: .7;flex-shrink: 0;}/* Blinking cursor while the answer streams in */.bubble.streaming::after {content: '\258D';color: var(--accent);margin-left: 2px;animation: cursor-blink 1s steps(2, start) infinite;}@keyframes cursor-blink { to { visibility: hidden; } }.typing-dots span {display: inline-block;width: 7px; height: 7px;32 unmodified linesline-height: 1.5;padding: 11px 14px;max-height: 140px;overflow-y: hidden; /* JS enables scrolling only once max-height is reached */transition: border-color .2s;}19 unmodified lines.btn-send:hover:not(:disabled) { background: var(--accent-dk); }.btn-send:active:not(:disabled){ transform: scale(.93); }.btn-send:disabled { opacity: .45; cursor: not-allowed; }.btn-send.stopping { background: #c0392b; color: #fff; }.btn-send.stopping:hover { background: #a93226; }/* ββ Reference images ββ */.ref-img-label {31 unmodified lines.ref-img:hover { opacity: .85; }/* ββ PDF reference preview modal ββ */.pdf-modal {position: fixed;inset: 0;z-index: 55;display: flex;align-items: center;justify-content: center;padding: 20px;}.pdf-modal-backdrop {position: absolute;inset: 0;background: rgba(0, 0, 0, .65);}.pdf-modal-panel {position: relative;width: min(920px, 96vw);height: 90vh;background: var(--surface);border: 1px solid var(--border);border-radius: 14px;display: flex;flex-direction: column;overflow: hidden;box-shadow: 0 24px 60px rgba(0, 0, 0, .55);}.pdf-toolbar {display: flex;align-items: center;gap: 12px;padding: 10px 14px;background: var(--surface2);border-bottom: 1px solid var(--border);}.pdf-title {flex: 1;min-width: 0;font-size: .85rem;font-weight: 600;color: var(--accent);white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}.pdf-nav, .pdf-actions {display: flex;align-items: center;gap: 6px;flex-shrink: 0;}.pdf-page-label {font-size: .8rem;color: var(--text-muted);min-width: 56px;text-align: center;}.pdf-btn {display: flex;align-items: center;justify-content: center;width: 30px;height: 30px;background: var(--surface);border: 1px solid var(--border);border-radius: 8px;color: var(--text);font-size: .95rem;line-height: 1;cursor: pointer;text-decoration: none;transition: border-color .15s, color .15s;}.pdf-btn:hover:not(:disabled) { border-color: var(--accent); }.pdf-btn:disabled { opacity: .35; cursor: not-allowed; }.pdf-body {flex: 1;overflow: auto;background: var(--pdf-bg);padding: 18px;position: relative;}.pdf-canvas-wrap {position: relative;width: fit-content;margin: 0 auto;box-shadow: 0 8px 30px rgba(0, 0, 0, .5);}.pdf-canvas-wrap canvas { display: block; }.pdf-highlight-layer {position: absolute;inset: 0;pointer-events: none;}.pdf-highlight {position: absolute;background: rgba(255, 213, 0, .40);border-radius: 2px;mix-blend-mode: multiply;}.pdf-loading {position: absolute;inset: 0;display: flex;align-items: center;justify-content: center;background: rgba(10, 12, 18, .6);}@media (max-width: 820px) {.pdf-modal { padding: 0; }.pdf-modal-panel {width: 100vw;height: 100vh;height: 100dvh;border-radius: 0;border: none;}.pdf-body { padding: 10px; }}/* ββ Starter question chips ββ */.starter-chips {display: flex;flex-wrap: wrap;gap: 8px;margin-top: 10px;}.starter-chip {font-size: .8rem;font-family: var(--font);padding: 7px 12px;border-radius: 20px;background: var(--surface2);border: 1px solid var(--border);color: var(--text);cursor: pointer;transition: border-color .15s, background .15s;text-align: left;}.starter-chip:hover { border-color: var(--accent); background: rgba(118, 185, 0, .08); }/* ββ Feedback buttons ββ */.feedback-bar { display: flex; gap: 4px; margin-top: 6px; }.fb-btn {background: transparent;border: 1px solid transparent;border-radius: 8px;font-size: .85rem;padding: 2px 7px;cursor: pointer;opacity: .45;transition: opacity .15s, border-color .15s, background .15s;}.fb-btn:hover { opacity: 1; }.fb-btn.active {opacity: 1;border-color: var(--accent);background: rgba(118, 185, 0, .1);}/* ββ Voice input ββ */.btn-mic {display: flex;align-items: center;justify-content: center;width: 44px;height: 44px;background: var(--surface2);border: 1px solid var(--border);border-radius: 50%;font-size: 1.05rem;cursor: pointer;flex-shrink: 0;transition: border-color .2s;}.btn-mic:hover { border-color: var(--accent); }.btn-mic.recording {border-color: #e74c3c;background: rgba(231, 76, 60, .15);animation: mic-pulse 1.2s infinite;}@keyframes mic-pulse {0%, 100% { box-shadow: 0 0 0 0 rgba(231, 76, 60, .5); }50% { box-shadow: 0 0 0 8px rgba(231, 76, 60, 0); }}/* ββ Header buttons (export, theme) ββ */.header-btn {display: flex;align-items: center;justify-content: center;flex-shrink: 0;width: 38px;height: 38px;background: var(--surface2);border: 1px solid var(--border);border-radius: 10px;color: var(--text);font-size: 1rem;cursor: pointer;transition: border-color .2s;}.header-btn:hover { border-color: var(--accent); }.header-btn svg { width: 18px; height: 18px; }/* Floating theme toggle on the auth screen */.theme-fab {position: absolute;top: 18px;right: 18px;width: 42px;height: 42px;display: flex;align-items: center;justify-content: center;background: var(--surface);border: 1px solid var(--border);border-radius: 50%;color: var(--text);cursor: pointer;transition: border-color .2s, transform .15s;}.theme-fab:hover { border-color: var(--accent); transform: scale(1.06); }.theme-fab svg { width: 20px; height: 20px; }/* ββ Password field with show/hide eye ββ */.password-wrap { position: relative; display: flex; }.password-wrap .auth-input { flex: 1; padding-right: 44px; }.eye-btn {position: absolute;right: 6px;top: 50%;transform: translateY(-50%);width: 32px;height: 32px;display: flex;align-items: center;justify-content: center;background: none;border: none;color: var(--text-muted);cursor: pointer;border-radius: 8px;transition: color .15s;}.eye-btn:hover { color: var(--accent); }.eye-btn svg { width: 18px; height: 18px; }/* ββ Admin doc list with delete ββ */.doc-item { display: flex; align-items: center; gap: 6px; }.doc-name { flex: 1; min-width: 0; }.doc-del {background: none;border: none;color: var(--text-muted);font-size: 1rem;line-height: 1;cursor: pointer;padding: 0 2px;flex-shrink: 0;}.doc-del:hover { color: #ff9c9c; }/* ββ Analytics ββ */.btn-analytics {display: flex;align-items: center;justify-content: center;gap: 6px;width: 100%;padding: 10px;background: var(--surface2);color: var(--text);border: 1px solid var(--border);border-radius: var(--radius);font-size: .88rem;font-weight: 600;cursor: pointer;transition: border-color .2s, background .2s;}.btn-analytics:hover { border-color: var(--accent); background: rgba(118,185,0,.06); }.stats-panel { max-width: 620px; height: auto; max-height: 88vh; }.stats-body {padding: 18px;overflow-y: auto;font-size: .88rem;}.stat-grid {display: grid;grid-template-columns: repeat(auto-fit, minmax(105px, 1fr));gap: 10px;}.stat-card {display: flex;flex-direction: column;align-items: center;gap: 2px;background: var(--surface2);border: 1px solid var(--border);border-radius: 10px;padding: 12px 8px;}.stat-value { font-size: 1.35rem; font-weight: 700; color: var(--accent); }.stat-label { font-size: .7rem; color: var(--text-muted); text-align: center; }.stat-list {list-style: none;display: flex;flex-direction: column;gap: 5px;}.stat-list li {display: flex;justify-content: space-between;gap: 10px;font-size: .8rem;padding: 7px 10px;background: var(--surface2);border-radius: 8px;word-break: break-word;}.stat-doc { flex: 1; min-width: 0; }.stat-count { color: var(--accent); font-weight: 700; flex-shrink: 0; }/* ββ Auth extras ββ */.auth-link {background: none;border: none;color: var(--text-muted);font-size: .78rem;margin-top: 10px;cursor: pointer;text-decoration: underline;align-self: center;font-family: var(--font);}.auth-link:hover { color: var(--accent); }/* ββ Utility ββ */.hidden { display: none !important; }14 unmodified linesdisplay: flex;align-items: center;justify-content: center;background: radial-gradient(circle at 30% 20%, var(--auth-glow), var(--bg));z-index: 50;padding: 20px;}99 unmodified linesborder-radius: 8px;line-height: 1.5;}.auth-message.error { background: rgba(220,70,70,.12); color: var(--err-text); border: 1px solid rgba(220,70,70,.3); }.auth-message.success { background: rgba(118,185,0,.12); color: var(--ok-text); border: 1px solid rgba(118,185,0,.3); }/* ββ New chat button ββ */.btn-new-chat {38 unmodified linesborder-left: 3px solid transparent;transition: border-color .15s, background .15s;}.session-item:hover { background: var(--hover); }.session-item.active { border-left-color: var(--accent); background: var(--hover); }.session-title {flex: 1;4 unmodified linestext-overflow: ellipsis;}.session-del,.session-ren {background: none;border: none;color: var(--text-muted);4 unmodified linesopacity: 0;transition: opacity .15s, color .15s;}.session-ren { font-size: .85rem; }.session-item:hover .session-del,.session-item:hover .session-ren { opacity: 1; }.session-del:hover { color: #ff9c9c; }.session-ren:hover { color: var(--accent); }.session-rename-input {flex: 1;min-width: 0;background: var(--surface);border: 1px solid var(--accent);border-radius: 6px;color: var(--text);font-family: var(--font);font-size: .82rem;padding: 4px 6px;}.session-rename-input:focus { outline: none; }.session-empty {color: var(--text-muted);65 unmodified linesalign-items: center;gap: 12px;}.chat-header-text { min-width: 0; flex: 1; }.menu-btn {display: none;
10 unmodified lines11121310 unmodified linesnumpy>=2.0.0pydantic>=2.9.0supabase>=2.7.010 unmodified lines1112131410 unmodified linesnumpy>=2.0.0pydantic>=2.9.0supabase>=2.7.0rank_bm25>=0.2.2
22 unmodified lines23242526272822 unmodified linescreated_at timestamptz not null default now());create index if not exists idx_sessions_user on public.chat_sessions (user_id, updated_at desc);create index if not exists idx_messages_session on public.messages (session_id, created_at);22 unmodified lines23242526272829303122 unmodified linescreated_at timestamptz not null default now());-- User feedback on assistant answers: 'up', 'down', or nullalter table public.messages add column if not exists feedback text;create index if not exists idx_sessions_user on public.chat_sessions (user_id, updated_at desc);create index if not exists idx_messages_session on public.messages (session_id, created_at);
123version https://git-lfs.github.com/spec/v1oid sha256:0810bcd710c1b69a75592ea836ba17dff316f4168ac8c8e256641b24818434d3size 6340653123version https://git-lfs.github.com/spec/v1oid sha256:003e336e8087f09540a146b30aa52b4af85dd61cbcfa125457389ec9cc28f1adsize 6340653
123version https://git-lfs.github.com/spec/v1oid sha256:5bc3425b4d84694291cbe1b1d91062f45d733124a9e3919d4e8f87c202b9fa34size 1683761123version https://git-lfs.github.com/spec/v1oid sha256:7ef4e0d625f0abef366146255b35109af73a3d4d3c3ecd99c8e4577214d6cd53size 1682636
README.md+34-19
backend/db.py+129-2
backend/ingest.py+63
backend/main.py+158-21
backend/rag.py+281-27
eval_questions.jsonAdded+62
evaluate.pyAdded+82
frontend/admin.htmlAdded+409
frontend/index.html+56-7
frontend/script.js+749-70
frontend/style.css+537-14
requirements.txt+1
supabase_schema.sql+3
vector_db/index.faiss+1-1
vector_db/index.pkl+2-2