File size: 27,844 Bytes
a805048
 
 
 
 
 
cf263e5
 
95c1d8f
 
 
 
 
a805048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
"""
EvidenceGuard AI - Your Verified University Knowledge Assistant
Gradio application (entry point for local runs and Hugging Face Spaces).

    python app.py            -> http://127.0.0.1:7860
"""

from __future__ import annotations
import spaces

@spaces.GPU(duration=30)
def _zerogpu_check():
    return True
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"

EXAMPLES = [
    "What is the minimum attendance required to appear for end-semester examinations?",
    "How many books can a postgraduate student borrow from the library?",
    "What is the fee for revaluation of answer scripts?",
    "Given that internal assessment carries 50 marks, how many marks does the end-semester examination carry?",
    "What is the late fee for course registration?",
    "Are late assignment submissions accepted?",
    "When is Internal Test 1 held this semester, and what must a student do to take a make-up test if they miss it through illness?",
]

DECISION_BADGE = {
    "answered": "βœ… Answered - evidence verified",
    "partial": "🟑 Partially answered - some parts not covered",
    "conflict": "⚠️ Conflicting evidence - both versions shown",
    "abstained": "β›” Abstained - insufficient evidence",
}

# ============================================================================ helpers

def kb_table() -> pd.DataFrame:
    rows = [{"Document": d.doc_name, "Title": d.title, "Issued": d.issued or "-", "Pages": d.pages,
             "Chunks": d.chunks, "Status": d.status} for d in SYSTEM.kb.docs.values()]
    return pd.DataFrame(rows, columns=["Document", "Title", "Issued", "Pages", "Chunks", "Status"])


def kb_summary() -> str:
    n_docs, n_chunks = len(SYSTEM.kb.docs), len(SYSTEM.kb.chunks)
    pages = sum(d.pages for d in SYSTEM.kb.docs.values())
    return f"**Knowledge base:** {n_docs} documents Β· {pages} pages Β· {n_chunks} chunks indexed in FAISS + BM25."


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()
    referential = re.match(r"^(and|what about|how about|also|then)\b", q, re.I) or \
        re.search(r"\b(it|that|this|those|them|they|same)\b", q, re.I)
    if referential or len(q.split()) <= 5:
        last = prev[-1]
        last = last.split("\n(Interpreted as:")[0]
        return f"{q} (context: {last})"
    return question


def citations_md(res: dict) -> str:
    if not res.get("citations"):
        return ""
    lines = [f"[{c['n']}] {c['title']} - *{c['doc_name']}*, page {c['page']}" for c in res["citations"]]
    return "\n\n**Sources:**\n" + "\n".join(f"- {x}" for x in lines)


def answer_md(res: dict, show_badge: bool = True) -> str:
    label = DECISION_BADGE.get(res["decision"], res["decision"])
    if res.get("sufficiency") is None and res["decision"] == "answered":
        label = "ℹ️ Answered without verification (baseline - may be unsupported)"
    badge = f"**{label}**\n\n" if show_badge else ""
    conf = f"\n\n<sub>Confidence: {res['confidence']:.2f} Β· {res['explanation']}</sub>" \
        if res.get("confidence") is not None else f"\n\n<sub>{res['explanation']}</sub>"
    return badge + res["answer"] + citations_md(res) + conf


def passages_df(res: dict) -> pd.DataFrame:
    rows = []
    for p in res.get("passages", []):
        rows.append({"#": p["n"], "Document": p["title"], "File": p["doc_name"], "Page": p["page"],
                     "Retrieval relevance": p["relevance"], "Dense": p["dense"], "BM25": p["sparse"],
                     "Source": p.get("source", "retrieval"),
                     "Passage": p["text"][:400] + ("..." if len(p["text"]) > 400 else "")})
    return pd.DataFrame(rows)


def verification_md(res: dict | None) -> str:
    if not res:
        return "*Ask a question in the AI Assistant tab (or below) to see its evidence report here.*"
    out = [f"### Question\n{res['question']}",
           f"### Decision\n**{DECISION_BADGE.get(res['decision'], res['decision'])}**",
           f"**Why:** {res['explanation']}"]
    s = res.get("sufficiency")
    if s:
        out.append("### Evidence sufficiency\n"
                   f"| Signal | Value | Threshold |\n|---|---|---|\n"
                   f"| Best passage relevance | {s['max_relevance']:.3f} | {SYSTEM.verifier.th['min_relevance']:.2f} |\n"
                   f"| Query coverage (combined) | {s['coverage']:.3f} | {SYSTEM.verifier.th['min_coverage']:.2f} |\n"
                   f"| Coverage by best single passage | {s['coverage_single']:.3f} | - |\n"
                   f"| Coverage by top-3 passages | {s['coverage_union']:.3f} | - |\n"
                   f"| Status | **{s['status']}** | - |\n\n"
                   + (f"Question terms not found in evidence: `{', '.join(s['missing_terms'])}`"
                      if s["missing_terms"] else "All question terms found in the evidence."))
    elif res["system"].startswith("1.") or res["system"].startswith("2."):
        out.append("*Baseline configuration: no sufficiency, contradiction or citation checks are performed.*")
    cs = res.get("conflicts") or []
    out.append("### Contradiction status\n" + ("No contradiction detected between the retrieved documents."
                                               if not cs else ""))
    for c in cs:
        out.append(f"- **{c['kind']} conflict** ({c['detail']})\n"
                   f"  - *{c['title_a']}* (p.{c['page_a']}, issued {c['issued_a'] or '?'}): {c['sentence_a']}\n"
                   f"  - *{c['title_b']}* (p.{c['page_b']}, issued {c['issued_b'] or '?'}): {c['sentence_b']}\n"
                   f"  - Newer document: **{c['newer'] or 'unknown'}**"
                   + (" (explicitly revises the earlier rule)" if c["explicit_update"] else ""))
    if res.get("premise_notes"):
        out.append("### False-premise check\n" + "\n".join(f"- {p}" for p in res["premise_notes"]))
    ch = res.get("citation_checks") or []
    if ch:
        out.append("### Citation verification\n| Sentence | Cited | Supported | Score | Reason |\n|---|---|---|---|---|\n" +
                   "\n".join(f"| {c['sentence'][:110].replace('|', '/')} | {c['cited']} | "
                             f"{'βœ…' if c['supported'] else '❌'} | {c['score']:.2f} | {c['reason'][:80]} |" for c in ch))
    t = res["timings"]
    out.append(f"### Timing\nretrieval {t['retrieval']*1000:.0f} ms Β· rerank {t.get('rerank', 0)*1000:.0f} ms Β· "
               f"verification {t.get('verification', 0)*1000:.0f} ms Β· generation {t['generation']*1000:.0f} ms Β· "
               f"**total {t['total']*1000:.0f} ms** Β· generator: {res.get('generator') or '-'}")
    return "\n\n".join(out)


# ============================================================================ callbacks

def process_uploads(files):
    if not files:
        return pd.DataFrame(), kb_table(), kb_summary(), "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 pd.DataFrame(), kb_table(), kb_summary(), "No PDF files were found in the upload."
    with LOCK:
        infos = SYSTEM.kb.add_pdfs(paths)
    rows = [{"File": i.doc_name, "Extraction status": f"{i.status}: {i.message}", "Pages": i.pages,
             "Chunks": i.chunks, "Detected title": i.title, "Detected date": i.issued or "-"} for i in infos]
    ok = sum(i.status == "ok" for i in infos)
    return (pd.DataFrame(rows), kb_table(), kb_summary(),
            f"Processed {len(infos)} file(s): {ok} indexed successfully. You can now ask questions 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 pd.DataFrame(), kb_table(), kb_summary(), "Knowledge base reset to the 16 synthetic sample documents."


def remove_doc(name):
    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_summary(), f"Removed {name}."
    return kb_table(), kb_summary(), f"Document '{name}' not found."


def chat(message, history, mode):
    history = history or []
    if not message or not message.strip():
        return history, "", None
    if not SYSTEM.kb.ready:
        history += [{"role": "user", "content": message},
                    {"role": "assistant", "content": "The knowledge base is empty. Upload PDFs in the Upload tab first."}]
        return history, "", None
    q = contextualize(message, history)
    key = "full" if mode.startswith("EvidenceGuard") else "baseline"
    with LOCK:
        res = SYSTEM.pipelines[key].answer(q)
    shown = message if q == message else f"{message}\n(Interpreted as: {q})"
    history += [{"role": "user", "content": shown}, {"role": "assistant", "content": answer_md(res)}]
    return history, "", res


def verify_direct(question, cfg):
    if not question.strip():
        return "Please type a question.", pd.DataFrame(), None
    key = {v: k for k, v in CONFIG_NAMES.items()}[cfg]
    with LOCK:
        res = SYSTEM.pipelines[key].answer(question)
    return verification_md(res), passages_df(res), res


def show_last(res):
    return verification_md(res), passages_df(res) if res else pd.DataFrame()


def compare(question):
    if not question.strip():
        empty = "Please type a question."
        return empty, empty, pd.DataFrame(), pd.DataFrame(), 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, "Decision": r["decision"], "Passages": len(r["passages"]),
                "Citations": len(r["citations"]), "Conflicts flagged": len(r.get("conflicts") or []),
                "Confidence": r.get("confidence"), "Retrieval ms": round((t["retrieval"] + t.get("rerank", 0)) * 1000, 1),
                "Verification ms": round(t.get("verification", 0) * 1000, 1),
                "Generation ms": round(t["generation"] * 1000, 1), "Total ms": round(t["total"] * 1000, 1)}
    perf_df = pd.DataFrame([perf(a, "Baseline RAG"), perf(b, "EvidenceGuard")])
    return answer_md(a, show_badge=False), answer_md(b), passages_df(a), passages_df(b), perf_df


# ---------------------------------------------------------------------------- evaluation dashboard
METRIC_LABELS = {
    "precision_at_k": "Precision@5", "recall_at_k": "Recall@5", "mrr": "MRR",
    "answer_correctness": "Answer correctness", "behaviour_accuracy": "Expected-behaviour accuracy",
    "faithfulness": "Faithfulness (to context)", "grounded_faithfulness": "Evidence-grounded faithfulness",
    "answer_relevance": "Answer relevance (lexical proxy)", "context_precision": "Context precision (AP@5)",
    "context_recall": "Context recall (key facts in context)", "unsupported_answer_rate": "Unsupported answer rate ↓",
    "abstention_accuracy": "Abstention accuracy", "abstention_f1": "Abstention F1",
    "contradiction_precision": "Contradiction precision", "contradiction_recall": "Contradiction recall",
    "contradiction_f1": "Contradiction F1", "citation_support_accuracy": "Citation support accuracy",
    "avg_response_time_s": "Avg response time (s)", "avg_retrieval_time_s": "Avg retrieval time (s)",
    "avg_generation_time_s": "Avg generation time (s)", "avg_verification_time_s": "Avg verification time (s)",
}


def load_eval(split="all"):
    p = config.RESULTS_DIR / "metrics.json"
    if not p.exists():
        return pd.DataFrame({"info": ["No results yet - click 'Re-run evaluation'."]}), "", pd.DataFrame(), pd.DataFrame(), pd.DataFrame()
    m = json.loads(p.read_text())
    names = m["config_names"]
    order = ["baseline", "rerank", "verify", "full"]
    rows = []
    for k, lab in METRIC_LABELS.items():
        rows.append({"Metric": lab, **{names[c]: m["metrics"][split][c].get(k) for c in order}})
    meta = m["meta"]
    info = (f"**Run:** {meta['date']} Β· {meta['n_questions']} questions ({meta['dev_questions']} dev used for "
            f"threshold calibration, {meta['test_questions']} held-out test) Β· backend `{meta['backend']}` Β· "
            f"runtime {meta['runtime_s']} s\n\n**Components used in this run:** " +
            "; ".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", "explanation"]] \
        if fails["evidenceguard_failures"] else pd.DataFrame()
    return pd.DataFrame(rows), info, cat, err, fdf


def chart_paths():
    names = ["retrieval_comparison", "answer_quality_comparison", "reliability_comparison",
             "category_breakdown", "error_analysis", "response_time"]
    return [str(config.CHARTS_DIR / f"{n}.png") if (config.CHARTS_DIR / f"{n}.png").exists() else None for n in names]


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." 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[-1800:] + "\n```", *load_eval(split), *chart_paths())


# ============================================================================ UI text
HOME_MD = f"""
# πŸ›‘οΈ EvidenceGuard AI
### Your Verified University Knowledge Assistant

**Problem.** Ordinary LLM chatbots and standard RAG systems answer *every* question, even when the
documents do not contain the answer, when the retrieved text is irrelevant, or when two documents give
**different versions of the same rule** (e.g. an old regulation and a newer amendment circular).
For students, a confident wrong answer about attendance, exam eligibility or scholarship deadlines has real consequences.

**EvidenceGuard AI** retrieves information from university documents and **verifies that sufficient,
consistent evidence exists before answering**. Otherwise it gives a partial answer, shows both
conflicting versions, or refuses and explains why.

#### Key features
- πŸ“„ Upload any PDFs; text extraction, cleaning, chunking and indexing (FAISS + BM25)
- πŸ”Ž Hybrid semantic + keyword retrieval with cross-encoder reranking
- πŸ§ͺ Evidence-sufficiency check β†’ **abstains** instead of guessing
- βš–οΈ **Conflict search**: detects contradictions between documents and names the newer version
- πŸ”— **Citation validation**: every answer sentence is checked against the passage it cites
- πŸ’¬ Explanations of why the system answered, partially answered or refused
- πŸ“Š Side-by-side Baseline vs EvidenceGuard comparison and a real evaluation dashboard

#### Research contribution
A training-free, CPU-only verification layer combining sufficiency-based abstention, numeric-aware
inter-document contradiction detection with *conflict-search retrieval*, and inference-time citation
validation, evaluated with a 4-configuration ablation on a 100-question benchmark containing labelled
missing, misleading and conflicting questions.

> ⚠️ The bundled documents describe **Aranya Valley University, a fictional institution**. They are
> SYNTHETIC DEMONSTRATION DATA, not real university policy.
"""

ABOUT_PARTS = []


def about_md():
    lit = "| # | Paper | Authors (year) | Venue | Problem | Method | Limitation | How EvidenceGuard responds |\n|---|---|---|---|---|---|---|---|\n"
    for i, p in enumerate(PAPERS, 1):
        lit += (f"| {i} | [{p['title']}]({p['link']}) | {p['authors']} ({p['year']}) | {p['venue']} | {p['problem']} | "
                f"{p['method']} | {p['limitations']} | {p['ours']} |\n")
    refs = "\n".join(f"{i}. {p['authors']}, \"{p['title']},\" {p['venue']}. {p['link']}" for i, p in enumerate(PAPERS, 1))
    refs += "\n" + "\n".join(f"{len(PAPERS) + i}. {r}" for i, r in enumerate(FOUNDATION, 1))
    return f"""
## Research papers (verified, 2023-2024)
{lit}

## Research gap
{RESEARCH_GAP}

## Objectives
{chr(10).join(f'{i}. {o}' for i, o in enumerate(OBJECTIVES, 1))}

## Methodology
1. **Synthetic corpus** - 16 fictional AVU PDFs (28 pages) generated from one fact base, with 9 planted conflicts,
   superseding circulars, a distractor document and deliberately uncovered topics.
2. **Benchmark** - 100 questions (30 answerable, 20 multi-passage, 15 missing-information, 15 misleading, 20 conflicting),
   each with expected answer, key facts, evidence document/page, expected evidence status and behaviour.
3. **Systems** - Baseline RAG (dense FAISS β†’ LLM β†’ citations) vs EvidenceGuard (hybrid β†’ rerank β†’ sufficiency β†’
   conflict search & contradiction β†’ grounded generation β†’ citation validation β†’ confidence/abstention).
4. **Ablation** - 4 configurations; thresholds calibrated on a stratified DEV split (29 questions) only, results reported
   on all 100 and on the 71 held-out TEST questions.
5. **Metrics** - Precision/Recall@5, MRR, answer correctness, faithfulness, answer relevance, context precision/recall,
   unsupported-answer rate, abstention and contradiction P/R/F1, citation support accuracy, latency.

## Architecture
See the diagrams below. Every model component has an offline fallback so the app runs on any CPU.

## Limitations
{chr(10).join(f'- {x}' for x in LIMITATIONS)}

## Future scope
{chr(10).join(f'- {x}' for x in FUTURE)}

## References (IEEE style)
{refs}
"""


def stack_md():
    rows = "\n".join(f"| {k} | {v} |" for k, v in SYSTEM.component_names().items())
    return ("#### Technology stack (live - what this running instance is using)\n| Component | Implementation |\n|---|---|\n"
            + rows + "\n| UI | Gradio |\n| PDF processing | PyMuPDF (pypdf fallback) |\n\n"
            "If a Hugging Face model cannot be downloaded, the app automatically uses the offline fallback shown here.")


CSS = """
.gradio-container {max-width: 1280px !important}
.badge {font-size: 0.9em}
footer {visibility: hidden}
"""

# ============================================================================ layout
with gr.Blocks(title="EvidenceGuard AI") as demo:
    last_result = gr.State(None)
    gr.Markdown("<h2 style='margin:0'>πŸ›‘οΈ EvidenceGuard AI - Your Verified University Knowledge Assistant</h2>"
                "<span style='color:#b00020;font-size:0.85em'>Demo corpus = SYNTHETIC DEMONSTRATION DATA of a fictional university</span>")

    # ---------------------------------------------------------------- TAB 1
    with gr.Tab("🏠 Home"):
        with gr.Row():
            with gr.Column(scale=3):
                gr.Markdown(HOME_MD)
            with gr.Column(scale=2):
                gr.Markdown(stack_md())
                home_kb = gr.Markdown(kb_summary())
        gr.Markdown("#### System workflow")
        gr.Image(str(ASSETS / "workflow.png"), show_label=False, height=620)

    # ---------------------------------------------------------------- TAB 2
    with gr.Tab("πŸ“„ Upload Documents"):
        gr.Markdown("Upload one or more PDFs. They are extracted, cleaned, chunked and added to the FAISS + BM25 index "
                    "alongside the sample documents. Re-uploading a file with the same name replaces it.")
        with gr.Row():
            up_files = gr.File(label="PDF files", file_count="multiple", file_types=[".pdf"])
            with gr.Column():
                up_btn = gr.Button("βš™οΈ Process documents into the vector database", variant="primary")
                reset_btn = gr.Button("↩️ Reset to sample data")
                up_status = gr.Markdown()
        up_result = gr.Dataframe(label="Processing result (this upload)", interactive=False)
        up_kb_md = gr.Markdown(kb_summary())
        up_kb = gr.Dataframe(value=kb_table(), label="Documents in the knowledge base", interactive=False)
        with gr.Row():
            rm_name = gr.Textbox(label="Remove a document (file name)", placeholder="e.g. my_policy.pdf")
            rm_btn = gr.Button("πŸ—‘οΈ Remove")

    # ---------------------------------------------------------------- TAB 3
    with gr.Tab("πŸ’¬ AI Assistant"):
        with gr.Row():
            mode = gr.Radio(["EvidenceGuard (verified)", "Baseline RAG"], value="EvidenceGuard (verified)",
                            label="Answering system")
        chatbot = gr.Chatbot(height=470, label="EvidenceGuard Assistant", render_markdown=True)
        with gr.Row():
            msg = gr.Textbox(placeholder="Ask about attendance, exams, scholarships, library rules... "
                                         "(follow-up questions are supported)", scale=6, show_label=False)
            send = gr.Button("Ask", variant="primary", scale=1)
            clear = gr.Button("Clear chat", scale=1)
        gr.Examples(EXAMPLES, inputs=msg, label="Try these (include missing-information, misleading and conflicting cases)")
        gr.Markdown("*The full evidence report for the latest answer is in the **Evidence Verification** tab.*")

    # ---------------------------------------------------------------- TAB 4
    with gr.Tab("πŸ”¬ Evidence Verification"):
        gr.Markdown("Shows the retrieved passages, sources, pages, relevance scores, evidence sufficiency, "
                    "contradiction status, citation verification and the reason for any abstention.")
        with gr.Row():
            v_q = gr.Textbox(label="Question", placeholder="Type a question, or press 'Show latest chat answer'", scale=4)
            v_cfg = gr.Dropdown(list(CONFIG_NAMES.values()), value=CONFIG_NAMES["full"], label="Configuration", scale=2)
        with gr.Row():
            v_btn = gr.Button("πŸ” Verify this question", variant="primary")
            v_last = gr.Button("Show latest chat answer")
        v_md = gr.Markdown(verification_md(None))
        v_df = gr.Dataframe(label="Retrieved passages", interactive=False, wrap=True)

    # ---------------------------------------------------------------- TAB 5
    with gr.Tab("βš–οΈ Model Comparison"):
        with gr.Row():
            c_q = gr.Textbox(label="Question", scale=5, value=EXAMPLES[0])
            c_btn = gr.Button("Compare", variant="primary", scale=1)
        gr.Examples(EXAMPLES, inputs=c_q)
        with gr.Row():
            with gr.Column():
                gr.Markdown("### System A - Baseline RAG")
                c_a = gr.Markdown()
                c_pa = gr.Dataframe(label="Baseline evidence", interactive=False, wrap=True)
            with gr.Column():
                gr.Markdown("### System B - EvidenceGuard RAG")
                c_b = gr.Markdown()
                c_pb = gr.Dataframe(label="EvidenceGuard evidence", interactive=False, wrap=True)
        c_perf = gr.Dataframe(label="Performance information", interactive=False)

    # ---------------------------------------------------------------- TAB 6
    with gr.Tab("πŸ“Š Evaluation Dashboard"):
        with gr.Row():
            e_split = gr.Radio(["all", "test", "dev"], value="all", label="Question split")
            e_reload = gr.Button("Reload results")
            e_run = gr.Button("▢️ Re-run evaluation (100 questions Γ— 4 systems)", variant="primary")
        e_status = gr.Markdown()
        e_info = gr.Markdown()
        e_table = gr.Dataframe(label="Metrics (real values from results/metrics.json)", interactive=False)
        with gr.Row():
            ch1 = gr.Image(label="Retrieval comparison")
            ch2 = gr.Image(label="Answer quality & faithfulness")
        with gr.Row():
            ch3 = gr.Image(label="Reliability: unsupported answers, abstention, contradictions")
            ch4 = gr.Image(label="Behaviour accuracy by category")
        with gr.Row():
            ch5 = gr.Image(label="Error analysis")
            ch6 = gr.Image(label="Response time")
        e_cat = gr.Dataframe(label="Category breakdown", interactive=False)
        e_err = gr.Dataframe(label="Error analysis (counts per configuration)", interactive=False)
        e_fail = gr.Dataframe(label="EvidenceGuard failure cases", interactive=False, wrap=True)

    # ---------------------------------------------------------------- TAB 7
    with gr.Tab("ℹ️ About Project"):
        gr.Markdown(about_md())
        gr.Image(str(ASSETS / "architecture.png"), label="System architecture")

    # ================================================================ wiring
    up_btn.click(process_uploads, up_files, [up_result, up_kb, up_kb_md, up_status]).then(kb_summary, None, home_kb)
    reset_btn.click(reset_kb, None, [up_result, up_kb, up_kb_md, up_status]).then(kb_summary, None, home_kb)
    rm_btn.click(remove_doc, rm_name, [up_kb, up_kb_md, up_status])
    send.click(chat, [msg, chatbot, mode], [chatbot, msg, last_result])
    msg.submit(chat, [msg, chatbot, mode], [chatbot, msg, last_result])
    clear.click(lambda: ([], None), None, [chatbot, last_result])
    v_btn.click(verify_direct, [v_q, v_cfg], [v_md, v_df, last_result])
    v_last.click(show_last, last_result, [v_md, v_df])
    c_btn.click(compare, c_q, [c_a, c_b, c_pa, c_pb, c_perf])
    eval_outs = [e_table, e_info, e_cat, e_err, e_fail]
    e_reload.click(load_eval, e_split, eval_outs).then(chart_paths, None, [ch1, ch2, ch3, ch4, ch5, ch6])
    e_split.change(load_eval, e_split, eval_outs)
    e_run.click(rerun_eval, e_split, [e_status, *eval_outs, ch1, ch2, ch3, ch4, ch5, ch6])
    demo.load(load_eval, e_split, eval_outs).then(chart_paths, None, [ch1, ch2, ch3, ch4, ch5, ch6])


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"), css=CSS, show_error=True, allowed_paths=[str(ASSETS), str(config.CHARTS_DIR)])