Spaces:
Running on Zero

File size: 41,611 Bytes
a805048
 
 
 
e0172ff
a805048
e0172ff
 
 
 
 
 
 
 
 
 
 
 
 
 
a805048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0172ff
 
 
 
 
 
 
 
a805048
e0172ff
a805048
 
 
e0172ff
 
 
 
 
 
a805048
 
e0172ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a805048
 
e0172ff
 
 
 
 
 
 
a805048
 
e0172ff
 
 
 
a805048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0172ff
 
 
 
 
a805048
 
 
e0172ff
a805048
 
e0172ff
a805048
 
e0172ff
 
 
 
 
 
 
 
 
a805048
e0172ff
 
 
 
 
 
 
 
 
 
 
 
a805048
 
e0172ff
a805048
e0172ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a805048
e0172ff
 
 
 
 
 
 
 
 
 
 
 
a805048
 
e0172ff
 
 
 
 
 
 
a805048
e0172ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a805048
 
e0172ff
 
 
 
 
 
 
 
a805048
e0172ff
 
 
 
 
 
 
 
 
 
 
 
a805048
 
 
 
 
 
e0172ff
a805048
 
 
 
 
 
 
 
 
e0172ff
a805048
 
e0172ff
 
 
 
 
 
a805048
 
 
 
 
 
 
 
e0172ff
a805048
 
 
e0172ff
 
a805048
 
 
 
e0172ff
 
a805048
 
 
 
 
e0172ff
a805048
 
e0172ff
 
a805048
e0172ff
a805048
 
e0172ff
 
a805048
 
 
e0172ff
 
a805048
 
 
e0172ff
a805048
 
 
e0172ff
 
a805048
 
 
 
 
 
e0172ff
 
 
 
a805048
 
e0172ff
a805048
e0172ff
 
 
 
 
 
 
 
 
 
 
 
 
 
a805048
 
 
e0172ff
a805048
e0172ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a805048
 
e0172ff
 
a805048
e0172ff
 
 
 
a805048
 
 
 
e0172ff
a805048
e0172ff
 
 
 
 
 
 
 
 
a805048
 
 
e0172ff
 
a805048
 
 
 
 
 
 
e0172ff
 
a805048
 
e0172ff
 
 
 
 
 
 
 
 
 
 
 
a805048
 
e0172ff
 
 
 
 
 
 
 
 
 
a805048
e0172ff
 
 
 
 
 
 
 
 
a805048
e0172ff
 
 
 
 
 
a805048
e0172ff
 
 
 
a805048
e0172ff
a805048
 
e0172ff
a805048
e0172ff
a805048
e0172ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a805048
 
 
e0172ff
 
 
 
 
 
a805048
e0172ff
 
a805048
 
e0172ff
a805048
e0172ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a805048
 
 
 
 
e0172ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a805048
e0172ff
 
 
 
a805048
 
e0172ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a805048
e0172ff
 
a805048
 
 
 
 
e0172ff
 
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
"""
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"<span class='eg-pill eg-{cls}'>{esc(label)}</span>"


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"<div class='eg-kb'>📚 <b>{n}</b> documents &nbsp;·&nbsp; <b>{p}</b> pages &nbsp;·&nbsp; "
            f"<b>{c}</b> searchable passages</div>")


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<sub>📎 " + " · ".join(f"[{c['n']}] {c['title']}, p.{c['page']}" for c in res["citations"]) + "</sub>"


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 ("<div class='eg-card eg-empty'><div class='eg-card-title'>Answer check</div>"
                "<p>Ask a question and this panel will show whether the answer is verified, "
                "how confident the assistant is, and which documents it used.</p></div>")
    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"<div class='eg-label'>Confidence</div><div class='eg-bar'><div style='width:{pct}%'></div></div>"
               f"<div class='eg-small'>{pct}%</div>")
    srcs = "".join(f"<li><b>[{c['n']}]</b> {esc(c['title'])} <span class='eg-muted'>· page {c['page']}</span></li>"
                   for c in res.get("citations", [])) or "<li class='eg-muted'>No sources cited</li>"
    conflicts = res.get("conflicts") or []
    conf_html = ""
    if conflicts:
        c = conflicts[0]
        conf_html = (f"<div class='eg-label'>Disagreement</div><div class='eg-small'>{esc(nice_detail(c['detail']))}"
                     f"<br>Newer document: <b>{esc(c['newer'] or 'unknown')}</b></div>")
    und = f"<div class='eg-small eg-muted'>Understood as: {esc(understood)}</div>" if understood else ""
    return (f"<div class='eg-card'><div class='eg-card-title'>Answer check</div>{pill(key)}"
            f"<p class='eg-small'>{esc(meaning)}</p>{und}{bar}{conf_html}"
            f"<div class='eg-label'>Sources used</div><ul class='eg-list'>{srcs}</ul></div>")


def step(n: int, title: str, ok: bool | None, body: str) -> str:
    icon = {True: "✅", False: "⚠️", None: "➖"}[ok]
    return (f"<div class='eg-step'><div class='eg-step-n'>{n}</div><div class='eg-step-body'>"
            f"<div class='eg-step-title'>{icon} {esc(title)}</div>{body}</div></div>")


def verification_html(res: dict | None) -> str:
    """'How it decided' page: the pipeline as five easy steps."""
    if not res:
        return ("<div class='eg-card eg-empty'><p>Nothing to show yet. Ask something on the <b>Ask</b> page, "
                "or type a question above and press <b>Check</b>.</p></div>")
    key = status_of(res)
    head = (f"<div class='eg-card'><div class='eg-q'>“{esc(res['question'])}”</div>{pill(key)}"
            f"<p class='eg-small'>{esc(res['explanation'])}</p></div>")
    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"<p>Found <b>{len(ps)}</b> relevant passages (best match: <i>{esc(top)}</i>)."
              + (f" Then searched again and pulled <b>{extra}</b> passages from other documents to look for disagreements."
                 if extra else "") + "</p>")
    s = res.get("sufficiency")
    if s:
        cov = int(round(s["coverage"] * 100))
        miss = (f" Question words not found in the evidence: <code>{esc(', '.join(s['missing_terms']))}</code>."
                if s["missing_terms"] else "")
        s2 = step(2, "Is there enough evidence?", s["status"] == "sufficient",
                  f"<p>The passages cover <b>{cov}%</b> of the question. Result: <b>{esc(s['status'])}</b>.{miss}</p>")
    else:
        s2 = step(2, "Is there enough evidence?", None, "<p>Skipped (normal RAG mode does not check).</p>")
    cs = res.get("conflicts") or []
    if s is None:
        s3 = step(3, "Do the documents disagree?", None, "<p>Skipped (normal RAG mode does not check).</p>")
    elif not cs:
        s3 = step(3, "Do the documents disagree?", True, "<p>No disagreement found.</p>")
    else:
        rows = "".join(
            f"<div class='eg-vs'><div><b>{esc(c['title_a'])}</b><span class='eg-muted'> · {esc(c['issued_a'] or '?')}</span>"
            f"<p>{esc(c['sentence_a'])}</p></div><div class='eg-vs-mid'>vs</div>"
            f"<div><b>{esc(c['title_b'])}</b><span class='eg-muted'> · {esc(c['issued_b'] or '?')}</span>"
            f"<p>{esc(c['sentence_b'])}</p></div></div>"
            f"<p class='eg-small'>Newer document: <b>{esc(c['newer'] or 'unknown')}</b>"
            + (" (it explicitly revises the older rule)" if c["explicit_update"] else "") + "</p>" 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"<p>{esc(p)}</p>" for p in pn) if pn else
              ("<p>No wrong assumption detected.</p>" if s else "<p>Skipped (normal RAG mode does not check).</p>"))
    ch = res.get("citation_checks") or []
    if ch:
        good = sum(c["supported"] for c in ch)
        lines = "".join(f"<li>{'✅' if c['supported'] else '❌'} {esc(c['sentence'][:140])}</li>" for c in ch)
        s5 = step(5, f"Are the citations real? {good} of {len(ch)} sentences supported", good == len(ch),
                  f"<ul class='eg-list'>{lines}</ul>")
    else:
        s5 = step(5, "Are the citations real?", None,
                  "<p>No answer sentences to check (the assistant refused)." if s else
                  "<p>Skipped (normal RAG mode does not check).</p>")
    t = res["timings"]
    foot = f"<p class='eg-small eg-muted'>Total time: {t['total']*1000:.0f} ms · Generator: {esc(res.get('generator') or '-')}</p>"
    return head + "<div class='eg-card'>" + s1 + s2 + s3 + s4 + s5 + foot + "</div>"


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 "<div class='eg-card'>No results yet. Use 'Re-run evaluation' below.</div>"
    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"<div class='eg-kpi'><div class='eg-kpi-title'>{esc(title)}</div>"
                f"<div class='eg-kpi-row'><span class='eg-kpi-old'>{fmt(bv)}</span><span class='eg-arrow'>→</span>"
                f"<span class='eg-kpi-new {'eg-good' if better else ''}'>{fmt(fv)}</span></div>"
                f"<div class='eg-small eg-muted'>Normal RAG → EvidenceGuard</div></div>")
    return (f"<div class='eg-kpis'>"
            + 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"</div><p class='eg-small eg-muted'>Measured on {n} questions ({esc(split)} split) · "
              f"synthetic university documents · run {esc(m['meta']['date'])}</p>")


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 = """
<div class='eg-hero'>
  <div class='eg-hero-tag'>University knowledge assistant</div>
  <h1>Answers you can <span>trust</span>.</h1>
  <p>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.</p>
</div>
"""

FEATURES = """
<div class='eg-features'>
  <div class='eg-feature'><div class='eg-ficon'>✅</div><h3>Answers with sources</h3>
    <p>Every answer shows which document and page it came from, and each citation is checked.</p></div>
  <div class='eg-feature'><div class='eg-ficon'>⚠️</div><h3>Catches conflicting rules</h3>
    <p>If an old regulation and a new circular disagree, you see both and which one is newer.</p></div>
  <div class='eg-feature'><div class='eg-ficon'>⛔</div><h3>Doesn't make things up</h3>
    <p>If the documents don't contain the answer, it tells you instead of guessing.</p></div>
</div>
"""

HOW = """
<div class='eg-section-title'>How it works</div>
<div class='eg-how'>
  <div><b>1</b><span>Search</span><p>Finds the most relevant passages using meaning + keywords.</p></div>
  <div><b>2</b><span>Check</span><p>Is there enough evidence? Do any documents disagree?</p></div>
  <div><b>3</b><span>Answer</span><p>Writes the answer only from the evidence, with citations.</p></div>
  <div><b>4</b><span>Verify</span><p>Confirms each citation supports its sentence, or refuses.</p></div>
</div>
"""

FOOTER = ("<div class='eg-footer'>EvidenceGuard AI · MSc Data Science project, Dayananda Sagar University · "
          "Demo documents describe <b>Aranya Valley University, a fictional institution</b> "
          "(SYNTHETIC DEMONSTRATION DATA, not real policy).</div>")


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("<div class='eg-brand'>🛡️ Evidence<span>Guard</span> AI</div>")
        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("<div class='eg-intro'>Ask a question about the university documents. "
                    "The panel on the right shows <b>whether the answer is verified</b>.</div>")
            with gr.Row():
                with gr.Column(scale=7):
                    chatbot = gr.Chatbot(height=460, show_label=False, render_markdown=True,
                                         placeholder="<b>Ask anything about university rules</b><br>"
                                                     "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("<div class='eg-label'>Try an example</div>")
                    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("<div class='eg-intro'>A step-by-step look at the checks behind an answer. "
                    "It shows your <b>latest question</b> automatically, or you can type a new one.</div>")
            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("<div class='eg-intro'>The same question to a <b>normal RAG chatbot</b> and to "
                    "<b>EvidenceGuard</b>, side by side. Same documents, same search - "
                    "the only difference is the evidence checks.</div>")
            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("<div class='eg-col-head eg-col-a'>Normal RAG chatbot</div>")
                    c_a = gr.Markdown("*Press Compare to see the answer.*", elem_classes="eg-col-body")
                with gr.Column(elem_classes="eg-col"):
                    gr.HTML("<div class='eg-col-head eg-col-b'>🛡️ EvidenceGuard</div>")
                    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("<div class='eg-intro'>These are the documents the assistant searches. "
                    "<b>Add your own PDFs</b> or remove one to see how the answers change.</div>")
            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("<div class='eg-intro'>How well it works, measured on a 100-question test set with "
                    "known correct answers. These numbers are read live from <code>results/metrics.json</code>.</div>")
            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)])