"""
EvidenceGuard AI - Your Verified University Knowledge Assistant
Gradio application (entry point for local runs and Hugging Face Spaces).
python app.py -> http://localhost:7860
"""
# ---------------------------------------------------------------------------
# Hugging Face ZeroGPU needs one @spaces.GPU function at startup. This must stay
# at the very top of the file. On a laptop (no `spaces` package) it is skipped.
try:
import spaces
@spaces.GPU(duration=30)
def _zerogpu_check():
return True
except ImportError:
pass
# ---------------------------------------------------------------------------
import html
import json
import logging
import re
import shutil
import subprocess
import sys
import threading
from pathlib import Path
import gradio as gr
import pandas as pd
import config
from src.research import FOUNDATION, FUTURE, LIMITATIONS, OBJECTIVES, PAPERS, RESEARCH_GAP
from src.system import CONFIG_NAMES, EvidenceGuardSystem
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
log = logging.getLogger("app")
SYSTEM = EvidenceGuardSystem() # loads models (or fallbacks) + the synthetic sample corpus
LOCK = threading.Lock() # uploads rebuild the shared index
ASSETS = config.ROOT / "assets"
# Quick-try questions, grouped by what they demonstrate
QUICK = [
("๐ Normal question", "How many marks are allotted to internal assessment in a theory course?"),
("โ ๏ธ Conflicting rules", "What is the minimum attendance required to appear for end-semester examinations?"),
("โ Not in documents", "Who is the current Vice-Chancellor of Aranya Valley University?"),
("๐ง Wrong assumption", "Given that internal assessment carries 50 marks, how many marks does the end-semester examination carry?"),
]
EXAMPLES = [q for _, q in QUICK] + [
"How many books can a postgraduate student borrow from the library?",
"What is the last date to apply for a scholarship for 2025-26?",
"Are late assignment submissions accepted?",
]
STATUS = { # decision -> (label, css class, one-line meaning)
"answered": ("Verified answer", "ok", "The documents clearly support this answer."),
"partial": ("Partly answered", "warn", "Only part of the question is covered by the documents."),
"conflict": ("Conflicting rules found", "bad", "Two documents disagree. Both versions are shown."),
"abstained": ("Not in the documents", "off", "There isn't enough evidence, so the assistant did not guess."),
"baseline": ("Unverified answer", "off", "Normal RAG mode: no evidence checks were done."),
}
# ============================================================================ small helpers
def esc(x) -> str:
return html.escape(str(x if x is not None else ""))
def status_of(res: dict) -> str:
if res.get("sufficiency") is None and res["decision"] == "answered":
return "baseline"
return res["decision"]
def pill(key: str) -> str:
label, cls, _ = STATUS.get(key, (key, "off", ""))
return f"{esc(label)}"
def doc_names() -> list[str]:
return sorted(d.doc_name for d in SYSTEM.kb.docs.values())
def kb_table() -> pd.DataFrame:
rows = [{"Title": d.title, "File": d.doc_name, "Issued": d.issued or "-", "Pages": d.pages}
for d in SYSTEM.kb.docs.values()]
return pd.DataFrame(rows, columns=["Title", "File", "Issued", "Pages"])
def kb_counts() -> tuple[int, int, int]:
return (len(SYSTEM.kb.docs), sum(d.pages for d in SYSTEM.kb.docs.values()), len(SYSTEM.kb.chunks))
def kb_banner() -> str:
n, p, c = kb_counts()
return (f"
๐ {n} documents ยท {p} pages ยท "
f"{c} searchable passages
")
def msg_text(m) -> str:
"""Gradio 6 returns message content either as a string or as a list of typed parts."""
c = m.get("content") if isinstance(m, dict) else m
if isinstance(c, str):
return c
if isinstance(c, dict):
return c.get("text", "")
if isinstance(c, (list, tuple)):
return " ".join(msg_text({"content": x}) for x in c)
return str(c or "")
def contextualize(question: str, history: list) -> str:
"""Follow-up support: short / referential questions inherit the previous user question."""
prev = [msg_text(m) for m in history if isinstance(m, dict) and m.get("role") == "user"]
if not prev:
return question
q = question.strip()
n = len(q.split())
starts_like_followup = re.match(r"^(and|what about|how about|also|then|for)\b", q, re.I)
has_pronoun = re.search(r"\b(it|they|them|those|same)\b", q, re.I)
if (starts_like_followup and n <= 10) or (has_pronoun and n <= 8) or n <= 4:
return f"{q} (context: {prev[-1]})"
return question
def sources_md(res: dict) -> str:
if not res.get("citations"):
return ""
return "\n\n๐ " + " ยท ".join(f"[{c['n']}] {c['title']}, p.{c['page']}" for c in res["citations"]) + ""
def chat_md(res: dict) -> str:
"""What appears inside the chat bubble: status line + answer + compact sources."""
key = status_of(res)
if key == "conflict": # the answer text already opens with its own warning line
return res["answer"] + sources_md(res)
label = STATUS.get(key, ("", "", ""))[0]
icon = {"answered": "โ
", "partial": "๐ก", "abstained": "โ", "baseline": "โน๏ธ"}.get(key, "")
return f"**{icon} {label}**\n\n{res['answer']}{sources_md(res)}"
def nice_detail(detail: str) -> str:
"""'%: 75 vs 80 (context: ...)' -> '75% vs 80%'."""
core = detail.split(" (context")[0]
m = re.match(r"^(.+?): (.+?) vs (.+)$", core)
if not m:
return core
unit, a, b = m.groups()
if unit.strip() == "%":
return f"{a}% vs {b}%"
if unit.strip().isupper() and len(unit.strip()) <= 4:
return f"{unit} {a} vs {unit} {b}"
return f"{a} vs {b}"
# ============================================================================ HTML cards
def answer_card(res: dict | None, understood: str | None = None) -> str:
"""Right-hand panel on the Ask page."""
if not res:
return ("Answer check
"
"
Ask a question and this panel will show whether the answer is verified, "
"how confident the assistant is, and which documents it used.
")
key = status_of(res)
meaning = STATUS.get(key, ("", "", ""))[2]
conf = res.get("confidence")
bar = ""
if conf is not None:
pct = int(round(conf * 100))
bar = (f"Confidence
"
f"{pct}%
")
srcs = "".join(f"[{c['n']}] {esc(c['title'])} ยท page {c['page']}"
for c in res.get("citations", [])) or "No sources cited"
conflicts = res.get("conflicts") or []
conf_html = ""
if conflicts:
c = conflicts[0]
conf_html = (f"Disagreement
{esc(nice_detail(c['detail']))}"
f"
Newer document: {esc(c['newer'] or 'unknown')}
")
und = f"Understood as: {esc(understood)}
" if understood else ""
return (f"Answer check
{pill(key)}"
f"
{esc(meaning)}
{und}{bar}{conf_html}"
f"
Sources used
")
def step(n: int, title: str, ok: bool | None, body: str) -> str:
icon = {True: "โ
", False: "โ ๏ธ", None: "โ"}[ok]
return (f"{n}
"
f"
{icon} {esc(title)}
{body}
")
def verification_html(res: dict | None) -> str:
"""'How it decided' page: the pipeline as five easy steps."""
if not res:
return ("Nothing to show yet. Ask something on the Ask page, "
"or type a question above and press Check.
")
key = status_of(res)
head = (f"โ{esc(res['question'])}โ
{pill(key)}"
f"
{esc(res['explanation'])}
")
ps = res.get("passages", [])
extra = sum(p.get("source") == "conflict-search" for p in ps)
top = ps[0]["title"] if ps else "-"
s1 = step(1, "Searched the documents", bool(ps),
f"Found {len(ps)} relevant passages (best match: {esc(top)})."
+ (f" Then searched again and pulled {extra} passages from other documents to look for disagreements."
if extra else "") + "
")
s = res.get("sufficiency")
if s:
cov = int(round(s["coverage"] * 100))
miss = (f" Question words not found in the evidence: {esc(', '.join(s['missing_terms']))}."
if s["missing_terms"] else "")
s2 = step(2, "Is there enough evidence?", s["status"] == "sufficient",
f"The passages cover {cov}% of the question. Result: {esc(s['status'])}.{miss}
")
else:
s2 = step(2, "Is there enough evidence?", None, "Skipped (normal RAG mode does not check).
")
cs = res.get("conflicts") or []
if s is None:
s3 = step(3, "Do the documents disagree?", None, "Skipped (normal RAG mode does not check).
")
elif not cs:
s3 = step(3, "Do the documents disagree?", True, "No disagreement found.
")
else:
rows = "".join(
f"{esc(c['title_a'])} ยท {esc(c['issued_a'] or '?')}"
f"
{esc(c['sentence_a'])}
vs
"
f"
{esc(c['title_b'])} ยท {esc(c['issued_b'] or '?')}"
f"
{esc(c['sentence_b'])}
"
f"Newer document: {esc(c['newer'] or 'unknown')}"
+ (" (it explicitly revises the older rule)" if c["explicit_update"] else "") + "
" for c in cs)
s3 = step(3, f"Do the documents disagree? Yes - {len(cs)} conflict(s)", False, rows)
pn = res.get("premise_notes") or []
s4 = step(4, "Is the question's assumption correct?", (not pn) if s else None,
"".join(f"{esc(p)}
" for p in pn) if pn else
("No wrong assumption detected.
" if s else "Skipped (normal RAG mode does not check).
"))
ch = res.get("citation_checks") or []
if ch:
good = sum(c["supported"] for c in ch)
lines = "".join(f"{'โ
' if c['supported'] else 'โ'} {esc(c['sentence'][:140])}" for c in ch)
s5 = step(5, f"Are the citations real? {good} of {len(ch)} sentences supported", good == len(ch),
f"")
else:
s5 = step(5, "Are the citations real?", None,
"No answer sentences to check (the assistant refused)." if s else
"
Skipped (normal RAG mode does not check).
")
t = res["timings"]
foot = f"Total time: {t['total']*1000:.0f} ms ยท Generator: {esc(res.get('generator') or '-')}
"
return head + "" + s1 + s2 + s3 + s4 + s5 + foot + "
"
def passages_df(res: dict | None) -> pd.DataFrame:
if not res:
return pd.DataFrame()
return pd.DataFrame([{"#": p["n"], "Document": p["title"], "Page": p["page"],
"Relevance": p["relevance"], "Dense": p["dense"], "BM25": p["sparse"],
"Found by": p.get("source", "retrieval"),
"Passage": p["text"][:400] + ("..." if len(p["text"]) > 400 else "")}
for p in res.get("passages", [])])
# ============================================================================ callbacks
def process_uploads(files):
if not files:
return kb_table(), kb_banner(), gr.update(), "Please choose one or more PDF files first."
paths = []
for f in files:
src = Path(f if isinstance(f, str) else f.name)
if src.suffix.lower() != ".pdf":
continue
dst = config.UPLOAD_DIR / src.name
shutil.copy(src, dst)
paths.append(dst)
if not paths:
return kb_table(), kb_banner(), gr.update(), "No PDF files were found in the upload."
with LOCK:
infos = SYSTEM.kb.add_pdfs(paths)
ok = [i for i in infos if i.status == "ok"]
bad = [i for i in infos if i.status != "ok"]
msg = f"โ
Added {len(ok)} document(s): " + ", ".join(f"{i.title} ({i.pages} pages)" for i in ok) if ok else ""
if bad:
msg += ("\n\n" if msg else "") + "โ Could not read: " + ", ".join(f"{i.doc_name} ({i.message})" for i in bad)
return kb_table(), kb_banner(), gr.update(choices=doc_names(), value=None), msg + "\n\nYou can now ask about them."
def reset_kb():
with LOCK:
for d in list(SYSTEM.kb.docs):
SYSTEM.kb.docs.pop(d)
SYSTEM.kb.chunks = []
SYSTEM.kb.load_folder(config.SAMPLE_DATA_DIR)
return kb_table(), kb_banner(), gr.update(choices=doc_names(), value=None), "โฉ๏ธ Restored the 16 sample documents."
def remove_doc(name):
if not name:
return kb_table(), kb_banner(), gr.update(), "Choose a document to remove first."
with LOCK:
for did, d in list(SYSTEM.kb.docs.items()):
if d.doc_name == name:
SYSTEM.kb.remove_doc(did)
return kb_table(), kb_banner(), gr.update(choices=doc_names(), value=None), f"๐๏ธ Removed {name}."
return kb_table(), kb_banner(), gr.update(choices=doc_names(), value=None), f"Document '{name}' not found."
def chat(message, history, mode):
history = history or []
if not message or not message.strip():
return history, "", None, answer_card(None), gr.update()
if not SYSTEM.kb.ready:
history += [{"role": "user", "content": message},
{"role": "assistant", "content": "There are no documents yet. Add PDFs on the Documents page first."}]
return history, "", None, answer_card(None), gr.update()
q = contextualize(message, history)
key = "baseline" if mode.startswith("Normal") else "full"
with LOCK:
res = SYSTEM.pipelines[key].answer(q)
history += [{"role": "user", "content": message}, {"role": "assistant", "content": chat_md(res)}]
return history, "", res, answer_card(res, q if q != message else None), verification_html(res)
def verify_direct(question, cfg):
if not question or not question.strip():
return verification_html(None), pd.DataFrame(), None
key = {v: k for k, v in CONFIG_NAMES.items()}[cfg]
with LOCK:
res = SYSTEM.pipelines[key].answer(question)
return verification_html(res), passages_df(res), res
def compare(question):
if not question or not question.strip():
return "Please type a question.", "Please type a question.", pd.DataFrame()
with LOCK:
a = SYSTEM.pipelines["baseline"].answer(question)
b = SYSTEM.pipelines["full"].answer(question)
def perf(r, name):
t = r["timings"]
return {"System": name, "Result": STATUS[status_of(r)][0], "Sources cited": len(r["citations"]),
"Conflicts flagged": len(r.get("conflicts") or []), "Confidence": r.get("confidence"),
"Time (ms)": round(t["total"] * 1000, 1)}
return (chat_md(a), chat_md(b), pd.DataFrame([perf(a, "Normal RAG"), perf(b, "EvidenceGuard")]))
# ---------------------------------------------------------------------------- results page
METRIC_LABELS = {
"behaviour_accuracy": "Did the right thing (answer / refuse / flag conflict)",
"unsupported_answer_rate": "Unsupported (hallucinated) answers โ",
"contradiction_recall": "Conflicts caught",
"contradiction_precision": "Conflict warnings that were real",
"abstention_recall": "Missing-info questions correctly refused",
"abstention_precision": "Refusals that were justified",
"citation_support_accuracy": "Citations that really support the sentence",
"grounded_faithfulness": "Answer faithful to the evidence",
"answer_correctness": "Answer correctness",
"recall_at_k": "Right document found in top 5 (Recall@5)",
"precision_at_k": "Precision@5", "mrr": "MRR",
"context_precision": "Context precision", "context_recall": "Context recall",
"answer_relevance": "Answer relevance", "abstention_f1": "Abstention F1", "contradiction_f1": "Contradiction F1",
"avg_response_time_s": "Average response time (s)",
}
def _metrics():
p = config.RESULTS_DIR / "metrics.json"
return json.loads(p.read_text()) if p.exists() else None
def kpi_html(split: str = "test") -> str:
m = _metrics()
if not m:
return "No results yet. Use 'Re-run evaluation' below.
"
b, f = m["metrics"][split]["baseline"], m["metrics"][split]["full"]
n = f.get("n_questions", "")
def tile(title, key, lower_better=False):
bv, fv = b.get(key), f.get(key)
fmt = lambda v: "โ" if v is None else f"{v*100:.0f}%"
better = fv is not None and bv is not None and ((fv < bv) if lower_better else (fv > bv))
return (f"{esc(title)}
"
f"
{fmt(bv)}โ"
f"{fmt(fv)}
"
f"
Normal RAG โ EvidenceGuard
")
return (f""
+ tile("Did the right thing", "behaviour_accuracy")
+ tile("Hallucinated answers", "unsupported_answer_rate", lower_better=True)
+ tile("Conflicts caught", "contradiction_recall")
+ tile("Missing info correctly refused", "abstention_recall")
+ f"
Measured on {n} questions ({esc(split)} split) ยท "
f"synthetic university documents ยท run {esc(m['meta']['date'])}
")
def load_eval(split="test"):
m = _metrics()
if not m:
empty = pd.DataFrame({"info": ["No results yet - click 'Re-run evaluation'."]})
return kpi_html(split), empty, "", pd.DataFrame(), pd.DataFrame(), pd.DataFrame()
names = m["config_names"]
order = ["baseline", "rerank", "verify", "full"]
rows = [{"Metric": lab, **{names[c]: m["metrics"][split][c].get(k) for c in order}}
for k, lab in METRIC_LABELS.items()]
meta = m["meta"]
info = (f"**Run:** {meta['date']} ยท {meta['n_questions']} questions ({meta['dev_questions']} used to tune "
f"thresholds, {meta['test_questions']} held-out test) ยท backend `{meta['backend']}` ยท "
f"runtime {meta['runtime_s']} s\n\n**Components:** "
+ "; ".join(f"{k}: {v}" for k, v in meta["components"].items()) + f"\n\n> โ ๏ธ {meta['note']}")
cat = pd.read_csv(config.RESULTS_DIR / "category_breakdown.csv")
err = pd.read_csv(config.RESULTS_DIR / "error_analysis.csv")
fails = json.loads((config.RESULTS_DIR / "failure_cases.json").read_text())
fdf = pd.DataFrame(fails["evidenceguard_failures"])[["id", "category", "question", "error_type", "answer",
"expected_answer"]] \
if fails["evidenceguard_failures"] else pd.DataFrame()
return kpi_html(split), pd.DataFrame(rows), info, cat, err, fdf
CHARTS = [("category_breakdown", "Right behaviour by question type"),
("reliability_comparison", "Hallucination, refusal and conflict detection"),
("answer_quality_comparison", "Answer quality"),
("retrieval_comparison", "Finding the right documents"),
("error_analysis", "Types of mistakes"),
("response_time", "Response time")]
def chart_paths():
return [str(config.CHARTS_DIR / f"{n}.png") if (config.CHARTS_DIR / f"{n}.png").exists() else None
for n, _ in CHARTS]
def rerun_eval(split):
backend = SYSTEM.effective_backend
cmd = [sys.executable, str(config.ROOT / "scripts" / "run_evaluation.py"), "--backend", backend,
"--llm", "extractive" if SYSTEM.generator.llm is None else config.LLM_BACKEND]
proc = subprocess.run(cmd, capture_output=True, text=True, cwd=str(config.ROOT), timeout=3600)
status = ("โ
Evaluation finished - the numbers above are refreshed." if proc.returncode == 0
else "โ Evaluation failed:\n" + proc.stderr[-1500:])
if proc.returncode == 0:
SYSTEM.set_thresholds(config.load_thresholds(SYSTEM.effective_backend))
return (status + "\n\n```\n" + proc.stdout[-1500:] + "\n```", *load_eval(split), *chart_paths())
# ============================================================================ static page content
HERO = """
University knowledge assistant
Answers you can trust.
Ask about attendance, exams, scholarships or library rules. EvidenceGuard answers only when the
documents back it up, warns you when two rules disagree, and says so when the answer isn't there.
"""
FEATURES = """
โ
Answers with sources
Every answer shows which document and page it came from, and each citation is checked.
โ ๏ธ
Catches conflicting rules
If an old regulation and a new circular disagree, you see both and which one is newer.
โ
Doesn't make things up
If the documents don't contain the answer, it tells you instead of guessing.
"""
HOW = """
How it works
1SearchFinds the most relevant passages using meaning + keywords.
2CheckIs there enough evidence? Do any documents disagree?
3AnswerWrites the answer only from the evidence, with citations.
4VerifyConfirms each citation supports its sentence, or refuses.
"""
FOOTER = ("")
def about_summary() -> str:
return f"""
### What this project is
EvidenceGuard AI is a retrieval-augmented (RAG) assistant for university documents that adds an
**evidence-verification layer** before answering. It is compared against a normal RAG system on a
100-question test set with known answers, missing information, wrong assumptions and planted conflicts.
### Research gap
{RESEARCH_GAP}
### Objectives
{chr(10).join(f'{i}. {o}' for i, o in enumerate(OBJECTIVES, 1))}
"""
def about_papers() -> str:
t = "| # | Paper | Year | What it found | How EvidenceGuard builds on it |\n|---|---|---|---|---|\n"
for i, p in enumerate(PAPERS, 1):
t += f"| {i} | [{p['title']}]({p['link']}) | {p['year']} | {p['results']} | {p['ours']} |\n"
return t
def about_method() -> str:
return """
1. **Synthetic documents**: 16 PDFs of a fictional university, with 9 planted conflicts, newer circulars,
a distractor document and deliberately missing topics.
2. **Test questions**: 100 questions (30 answerable, 20 multi-passage, 15 missing-information,
15 wrong-assumption, 20 conflicting), each with the expected answer and expected behaviour.
3. **Two systems**: normal RAG (search โ LLM) vs EvidenceGuard (hybrid search โ rerank โ evidence check โ
conflict check โ grounded answer โ citation check โ answer / partial / conflict / refuse).
4. **Fair testing**: thresholds tuned on 29 questions only; results reported on the other 71.
"""
def about_refs() -> str:
refs = [f"{p['authors']}, \"{p['title']},\" {p['venue']}. {p['link']}" for p in PAPERS] + list(FOUNDATION)
return "\n".join(f"{i}. {r}" for i, r in enumerate(refs, 1))
def stack_md() -> str:
rows = "\n".join(f"| {k} | {v} |" for k, v in SYSTEM.component_names().items())
return ("| Component | What this running app is using |\n|---|---|\n" + rows +
"\n| Interface | Gradio |\n| PDF reading | PyMuPDF (pypdf fallback) |")
# ============================================================================ styling
CSS = """
.gradio-container {max-width: 1180px !important; margin: 0 auto !important}
footer {display: none !important}
/* top bar */
.eg-top {display:flex; align-items:center; justify-content:space-between; padding:6px 4px 2px}
.eg-brand {font-size:1.35rem; font-weight:800; letter-spacing:-0.02em}
.eg-brand span {color: var(--color-accent)}
.eg-kb {font-size:0.85rem; color: var(--body-text-color-subdued)}
/* tabs look like a website menu */
.eg-nav > .tab-wrapper button, .eg-nav button[role="tab"] {font-size:0.98rem !important; font-weight:600 !important; padding:10px 16px !important}
/* hero */
.eg-hero {text-align:center; padding:46px 16px 26px}
.eg-hero-tag {display:inline-block; font-size:0.8rem; font-weight:700; letter-spacing:0.06em; text-transform:uppercase;
color: var(--color-accent); border:1px solid var(--color-accent); border-radius:999px; padding:4px 12px; margin-bottom:14px}
.eg-hero h1 {font-size:2.7rem !important; line-height:1.1; margin:0 0 14px !important; font-weight:800}
.eg-hero h1 span {color: var(--color-accent)}
.eg-hero p {max-width:700px; margin:0 auto; font-size:1.08rem; color: var(--body-text-color-subdued)}
.eg-cta {max-width:420px; margin:0 auto !important}
/* feature cards */
.eg-features {display:grid; grid-template-columns:repeat(3,1fr); gap:16px; margin:26px 0 10px}
.eg-feature {border:1px solid var(--border-color-primary); border-radius:14px; padding:20px; background: var(--background-fill-primary)}
.eg-feature h3 {margin:6px 0 6px !important; font-size:1.05rem}
.eg-feature p {margin:0; color: var(--body-text-color-subdued); font-size:0.93rem}
.eg-ficon {font-size:1.6rem}
.eg-section-title {font-size:1.2rem; font-weight:700; margin:28px 0 12px; text-align:center}
.eg-how {display:grid; grid-template-columns:repeat(4,1fr); gap:12px}
.eg-how > div {border-radius:12px; padding:16px; background: var(--background-fill-secondary)}
.eg-how b {display:inline-flex; width:28px; height:28px; border-radius:50%; align-items:center; justify-content:center;
background: var(--color-accent); color:white; margin-right:8px}
.eg-how span {font-weight:700}
.eg-how p {margin:8px 0 0; font-size:0.9rem; color: var(--body-text-color-subdued)}
@media (max-width: 800px) {.eg-features, .eg-how {grid-template-columns:1fr}}
/* page intro line */
.eg-intro {font-size:1rem; color: var(--body-text-color-subdued); margin:4px 0 8px}
.eg-intro b {color: var(--body-text-color)}
/* cards */
.eg-card {border:1px solid var(--border-color-primary); border-radius:14px; padding:16px 18px; margin-bottom:12px;
background: var(--background-fill-primary)}
.eg-card p {margin:6px 0}
.eg-card-title {font-weight:700; font-size:1rem; margin-bottom:8px}
.eg-empty {color: var(--body-text-color-subdued)}
.eg-q {font-size:1.05rem; font-weight:600; margin-bottom:8px}
.eg-label {font-size:0.75rem; font-weight:700; text-transform:uppercase; letter-spacing:0.05em;
color: var(--body-text-color-subdued); margin:14px 0 4px}
.eg-small {font-size:0.88rem}
.eg-muted {color: var(--body-text-color-subdued)}
.eg-list {margin:4px 0 0 18px; padding:0; font-size:0.9rem}
.eg-list li {margin:3px 0}
.eg-bar {height:8px; border-radius:99px; background: var(--background-fill-secondary); overflow:hidden}
.eg-bar > div {height:100%; background: var(--color-accent); border-radius:99px}
/* status pills */
.eg-pill {display:inline-block; font-weight:700; font-size:0.85rem; padding:4px 12px; border-radius:999px}
.eg-ok {background:rgba(22,163,74,0.14); color:#15803d}
.eg-warn {background:rgba(202,138,4,0.16); color:#a16207}
.eg-bad {background:rgba(220,38,38,0.13); color:#b91c1c}
.eg-off {background:rgba(100,116,139,0.16); color:#475569}
.dark .eg-ok {color:#4ade80} .dark .eg-warn {color:#facc15} .dark .eg-bad {color:#f87171} .dark .eg-off {color:#cbd5e1}
/* steps */
.eg-step {display:flex; gap:14px; padding:12px 0; border-bottom:1px solid var(--border-color-primary)}
.eg-step:last-of-type {border-bottom:none}
.eg-step-n {flex:0 0 30px; height:30px; border-radius:50%; display:flex; align-items:center; justify-content:center;
font-weight:700; background: var(--background-fill-secondary)}
.eg-step-body {flex:1}
.eg-step-title {font-weight:700}
.eg-vs {display:grid; grid-template-columns:1fr auto 1fr; gap:10px; margin-top:8px}
.eg-vs > div:not(.eg-vs-mid) {border-radius:10px; padding:10px 12px; background: var(--background-fill-secondary); font-size:0.9rem}
.eg-vs-mid {align-self:center; font-weight:800; color: var(--body-text-color-subdued)}
/* KPI tiles */
.eg-kpis {display:grid; grid-template-columns:repeat(4,1fr); gap:14px}
.eg-kpi {border:1px solid var(--border-color-primary); border-radius:14px; padding:16px; background: var(--background-fill-primary)}
.eg-kpi-title {font-weight:600; font-size:0.92rem; margin-bottom:6px}
.eg-kpi-row {display:flex; align-items:baseline; gap:8px}
.eg-kpi-old {font-size:1.1rem; color: var(--body-text-color-subdued); text-decoration:line-through}
.eg-kpi-new {font-size:2rem; font-weight:800}
.eg-good {color:#16a34a}
.eg-arrow {color: var(--body-text-color-subdued)}
@media (max-width: 800px) {.eg-kpis {grid-template-columns:1fr 1fr}}
/* compare headers */
.eg-col-head {font-weight:700; font-size:1.05rem; padding:10px 14px; border-radius:12px 12px 0 0}
.eg-col-a {background: var(--background-fill-secondary)}
.eg-col-b {background: rgba(37,99,235,0.12)}
.eg-col {gap:0 !important; justify-content:flex-start !important}
.eg-col-head {border-radius:12px !important; margin-bottom:6px}
.eg-col-body {padding:4px 16px 12px !important; min-height:120px; border:none !important}
/* quick-try buttons */
.eg-quick button {font-size:0.85rem !important}
.eg-footer {text-align:center; font-size:0.8rem; color: var(--body-text-color-subdued); padding:22px 0 6px;
border-top:1px solid var(--border-color-primary); margin-top:26px}
"""
# ============================================================================ layout
with gr.Blocks(title="EvidenceGuard AI") as demo:
last_result = gr.State(None)
with gr.Row(elem_classes="eg-top"):
gr.HTML("๐ก๏ธ EvidenceGuard AI
")
top_kb = gr.HTML(kb_banner())
with gr.Tabs(elem_classes="eg-nav") as tabs:
# ------------------------------------------------------------ HOME
with gr.Tab("Home", id="home"):
gr.HTML(HERO)
with gr.Row(elem_classes="eg-cta"):
go_ask = gr.Button("Start asking โ", variant="primary", size="lg")
go_docs = gr.Button("Add your documents", size="lg")
gr.HTML(FEATURES)
gr.HTML(HOW)
# ------------------------------------------------------------ ASK
with gr.Tab("Ask", id="ask"):
gr.HTML("Ask a question about the university documents. "
"The panel on the right shows whether the answer is verified.
")
with gr.Row():
with gr.Column(scale=7):
chatbot = gr.Chatbot(height=460, show_label=False, render_markdown=True,
placeholder="Ask anything about university rules
"
"or try one of the examples below")
with gr.Row():
msg = gr.Textbox(placeholder="e.g. What is the minimum attendance required?",
show_label=False, scale=8, container=False)
send = gr.Button("Ask", variant="primary", scale=1, min_width=80)
gr.HTML("Try an example
")
with gr.Row(elem_classes="eg-quick"):
quick_btns = [gr.Button(label, size="sm") for label, _ in QUICK]
with gr.Column(scale=4):
card = gr.HTML(answer_card(None))
see_how = gr.Button("See how it decided โ", size="sm")
with gr.Accordion("Settings", open=False):
mode = gr.Radio(["EvidenceGuard (verified)", "Normal RAG (no checks)"],
value="EvidenceGuard (verified)", label="Answer mode")
clear = gr.Button("Clear chat", size="sm")
# ------------------------------------------------------------ HOW IT DECIDED
with gr.Tab("How it decided", id="how"):
gr.HTML("A step-by-step look at the checks behind an answer. "
"It shows your latest question automatically, or you can type a new one.
")
with gr.Row():
v_q = gr.Textbox(show_label=False, placeholder="Type a question to check", scale=6, container=False)
v_btn = gr.Button("Check", variant="primary", scale=1, min_width=80)
v_html = gr.HTML(verification_html(None))
with gr.Accordion("Technical details (retrieved passages and scores)", open=False):
v_cfg = gr.Dropdown(list(CONFIG_NAMES.values()), value=CONFIG_NAMES["full"],
label="System configuration (for the ablation study)")
v_df = gr.Dataframe(interactive=False, wrap=True)
# ------------------------------------------------------------ COMPARE
with gr.Tab("Compare", id="compare"):
gr.HTML("The same question to a normal RAG chatbot and to "
"EvidenceGuard, side by side. Same documents, same search - "
"the only difference is the evidence checks.
")
with gr.Row():
c_q = gr.Dropdown(EXAMPLES, value=EXAMPLES[1], allow_custom_value=True, show_label=False,
scale=6, container=False)
c_btn = gr.Button("Compare", variant="primary", scale=1, min_width=90)
with gr.Row():
with gr.Column(elem_classes="eg-col"):
gr.HTML("Normal RAG chatbot
")
c_a = gr.Markdown("*Press Compare to see the answer.*", elem_classes="eg-col-body")
with gr.Column(elem_classes="eg-col"):
gr.HTML("๐ก๏ธ EvidenceGuard
")
c_b = gr.Markdown("*Press Compare to see the answer.*", elem_classes="eg-col-body")
with gr.Accordion("Details", open=False):
c_perf = gr.Dataframe(interactive=False)
# ------------------------------------------------------------ DOCUMENTS
with gr.Tab("Documents", id="docs"):
gr.HTML("These are the documents the assistant searches. "
"Add your own PDFs or remove one to see how the answers change.
")
with gr.Row():
with gr.Column(scale=3):
up_files = gr.File(label="Drop PDF files here", file_count="multiple", file_types=[".pdf"])
up_btn = gr.Button("Add to knowledge base", variant="primary")
with gr.Column(scale=2):
rm_name = gr.Dropdown(doc_names(), label="Remove a document", value=None)
rm_btn = gr.Button("Remove selected")
reset_btn = gr.Button("Restore sample documents", size="sm")
doc_status = gr.Markdown()
kb_df = gr.Dataframe(value=kb_table(), label="Documents in the knowledge base", interactive=False, wrap=True,
column_widths=["46%", "38%", "10%", "6%"])
# ------------------------------------------------------------ RESULTS
with gr.Tab("Results", id="results"):
gr.HTML("How well it works, measured on a 100-question test set with "
"known correct answers. These numbers are read live from results/metrics.json.
")
e_split = gr.Radio(["test", "all", "dev"], value="test", label="Question set",
info="test = 71 questions never used for tuning (recommended)")
e_kpi = gr.HTML(kpi_html("test"))
with gr.Row():
ch_imgs = []
for n, lab in CHARTS[:2]:
ch_imgs.append(gr.Image(label=lab))
with gr.Accordion("More charts", open=False):
with gr.Row():
for n, lab in CHARTS[2:4]:
ch_imgs.append(gr.Image(label=lab))
with gr.Row():
for n, lab in CHARTS[4:6]:
ch_imgs.append(gr.Image(label=lab))
with gr.Accordion("All metrics (4 configurations)", open=False):
e_info = gr.Markdown()
e_table = gr.Dataframe(interactive=False, wrap=True)
with gr.Accordion("By question type, mistakes and failure cases", open=False):
e_cat = gr.Dataframe(label="By question type", interactive=False)
e_err = gr.Dataframe(label="Types of mistakes", interactive=False)
e_fail = gr.Dataframe(label="Questions EvidenceGuard got wrong", interactive=False, wrap=True)
with gr.Accordion("Re-run the evaluation", open=False):
gr.Markdown("Runs all 100 questions through all 4 configurations and recalculates every number.")
e_run = gr.Button("โถ๏ธ Re-run evaluation", variant="primary")
e_status = gr.Markdown()
# ------------------------------------------------------------ ABOUT
with gr.Tab("About", id="about"):
gr.Markdown(about_summary())
with gr.Accordion("How the project was done", open=False):
gr.Markdown(about_method())
gr.Image(str(ASSETS / "architecture.png"), label="System architecture")
with gr.Accordion("Research papers reviewed", open=False):
gr.Markdown(about_papers())
with gr.Accordion("Limitations and future work", open=False):
gr.Markdown("**Limitations**\n" + "\n".join(f"- {x}" for x in LIMITATIONS) +
"\n\n**Future work**\n" + "\n".join(f"- {x}" for x in FUTURE))
with gr.Accordion("Technology used", open=False):
gr.Markdown(stack_md())
with gr.Accordion("References", open=False):
gr.Markdown(about_refs())
gr.HTML(FOOTER)
# ================================================================ wiring
go_ask.click(lambda: gr.Tabs(selected="ask"), None, tabs)
go_docs.click(lambda: gr.Tabs(selected="docs"), None, tabs)
see_how.click(lambda: gr.Tabs(selected="how"), None, tabs)
chat_outs = [chatbot, msg, last_result, card, v_html]
send.click(chat, [msg, chatbot, mode], chat_outs).then(passages_df, last_result, v_df)
msg.submit(chat, [msg, chatbot, mode], chat_outs).then(passages_df, last_result, v_df)
for b, (_, q) in zip(quick_btns, QUICK):
b.click(lambda h, m, q=q: chat(q, h, m), [chatbot, mode], chat_outs).then(passages_df, last_result, v_df)
clear.click(lambda: ([], None, answer_card(None), verification_html(None)), None,
[chatbot, last_result, card, v_html])
v_btn.click(verify_direct, [v_q, v_cfg], [v_html, v_df, last_result])
v_q.submit(verify_direct, [v_q, v_cfg], [v_html, v_df, last_result])
c_btn.click(compare, c_q, [c_a, c_b, c_perf])
doc_outs = [kb_df, top_kb, rm_name, doc_status]
up_btn.click(process_uploads, up_files, doc_outs)
rm_btn.click(remove_doc, rm_name, doc_outs)
reset_btn.click(reset_kb, None, doc_outs)
eval_outs = [e_kpi, e_table, e_info, e_cat, e_err, e_fail]
e_split.change(load_eval, e_split, eval_outs)
e_run.click(rerun_eval, e_split, [e_status, *eval_outs, *ch_imgs])
demo.load(load_eval, e_split, eval_outs).then(chart_paths, None, ch_imgs)
if __name__ == "__main__":
demo.queue(default_concurrency_limit=2).launch(
server_name="0.0.0.0", server_port=int(__import__("os").getenv("PORT", 7860)),
theme=gr.themes.Soft(primary_hue="blue", font=[gr.themes.GoogleFont("Inter"), "sans-serif"]),
css=CSS, show_error=True, allowed_paths=[str(ASSETS), str(config.CHARTS_DIR)])