File size: 37,197 Bytes
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
"""
Builds the MSc project report content (reports/report_model.json) from the ACTUAL result files,
then renders DOCX (scripts/render_report_docx.js) and PDF (LibreOffice). Also refreshes the results
table in README.md. No number in the report is typed by hand - all are read from results/.

Usage: python scripts/build_report.py [--author "Name"] [--usn USN]
"""
import argparse
import json
import subprocess
import sys
from collections import Counter
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "scripts"))

from corpus_content import DOCUMENTS  # noqa: E402
from src.research import FOUNDATION, FUTURE, LIMITATIONS, OBJECTIVES, PAPERS, RESEARCH_GAP  # noqa: E402

RES = ROOT / "results"
M = json.loads((RES / "metrics.json").read_text())
SIG = json.loads((RES / "significance.json").read_text())
CAL = json.loads((RES / "calibrated_thresholds.json").read_text())
FAIL = json.loads((RES / "failure_cases.json").read_text())
QS = json.loads((ROOT / "evaluation_data" / "questions.json").read_text())
ORDER = ["baseline", "rerank", "verify", "full"]
NAMES = M["config_names"]
B = []   # blocks


def H1(t): B.append({"t": "h1", "text": t})
def H2(t): B.append({"t": "h2", "text": t})
def P(t): B.append({"t": "p", "text": t})
def BUL(items): B.append({"t": "bullets", "items": list(items)})
def NUM(items): B.append({"t": "numbers", "items": list(items)})
def TABLE(header, rows, widths=None, size=8): B.append({"t": "table", "header": header, "rows": rows, "widths": widths, "size": size})
def IMG(path, w=16, cap=""): B.append({"t": "img", "path": str(path), "width_cm": w, "caption": cap})
def CAP(t): B.append({"t": "caption", "text": t})
def BR(): B.append({"t": "pagebreak"})
def CODE(t): B.append({"t": "code", "text": t})


def plain(t):
    """Strip the app's markdown (bold/italic markers, list dashes, emoji badges) for report tables."""
    import re
    t = re.sub(r"\*{1,2}|(?<!\w)_(?!\w)", "", t.replace("\n", " "))
    return re.sub(r"\s+-\s+", " | ", t.replace("⚠️", "[!]")).strip()


def f(x, d=3):
    return "-" if x is None else f"{x:.{d}f}"


def m(split, cfg, key):
    return M["metrics"][split][cfg][key]


def build(author, usn, programme, institution):
    meta = M["meta"]
    A, T = "all", "test"
    sig_b = SIG["behaviour_accuracy|test|baseline_vs_full"]
    sig_u = SIG["unsupported_answer|test|baseline_vs_full"]
    sig_ba = SIG["behaviour_accuracy|all|baseline_vs_full"]

    # --------------------------------------------------------------- title page
    B.append({"t": "title", "title": "EvidenceGuard AI",
              "subtitle": "A Reliable University Knowledge Assistant Using Retrieval-Augmented Generation, "
                          "Large Language Models and Evidence Verification",
              "lines": ["MSc Project Report - Generative AI and Large Language Models",
                        f"Submitted by: {author}" + (f"  (USN: {usn})" if usn else ""),
                        programme, institution, "Guide: ______________________",
                        "November 2026"]})
    BR()

    # --------------------------------------------------------------- abstract
    H1("Abstract")
    P("Standard retrieval-augmented generation (RAG) assistants answer every question, even when the retrieved "
      "documents do not contain the answer or contain contradictory versions of the same rule. For students asking "
      "about attendance, examination eligibility or scholarship deadlines, a fluent but unsupported answer is a "
      "real risk. This project builds EvidenceGuard AI, a university knowledge assistant that verifies evidence "
      "before answering. It combines hybrid retrieval (FAISS dense vectors fused with BM25 by reciprocal rank "
      "fusion), cross-encoder reranking, an evidence-sufficiency check, a conflict-search retrieval step with "
      "numeric-aware contradiction detection, context-grounded generation, sentence-level citation validation and "
      "confidence-based abstention with natural-language explanations. Because no data was available, a corpus of "
      f"{len(DOCUMENTS)} explicitly fictional university PDFs (28 pages) and a 100-question benchmark with "
      "labelled answerable, multi-passage, missing-information, misleading and conflicting questions were "
      "generated from a single fact base. A four-configuration ablation was run on CPU with offline fallback "
      "components (Hugging Face downloads were unavailable in the build environment). On the 71 held-out test "
      f"questions, EvidenceGuard raised expected-behaviour accuracy from {m(T,'baseline','behaviour_accuracy'):.1%} "
      f"to {m(T,'full','behaviour_accuracy'):.1%} (exact McNemar p = {sig_b['mcnemar_exact_p']:.3f}) and reduced the "
      f"unsupported-answer rate from {m(T,'baseline','unsupported_answer_rate'):.1%} to "
      f"{m(T,'full','unsupported_answer_rate'):.1%} (p = {sig_u['mcnemar_exact_p']:.3f}), detecting conflicting "
      f"evidence with F1 = {m(T,'full','contradiction_f1'):.2f}. The gains come from the verification layer; "
      "reranking alone gave no improvement, and verification costs some over-abstention on answerable "
      "multi-part questions. All results use synthetic data and do not establish accuracy on real university "
      "policies. The system is delivered as a seven-tab Gradio application prepared for Hugging Face Spaces.")
    P("Keywords: retrieval-augmented generation, hallucination, abstention, contradiction detection, citation "
      "verification, natural language inference, FAISS, Gradio.")
    BR()

    # --------------------------------------------------------------- 1-3
    H1("1. Introduction")
    P("Large language models (LLMs) generate fluent text but can hallucinate. Retrieval-augmented generation "
      "[9] reduces this by conditioning the model on retrieved passages, and it has become the default design for "
      "institutional chatbots. Universities are a natural application: rules on attendance, assessment, "
      "scholarships and libraries are spread across regulations, amendment circulars, notices and handbooks that "
      "change every year. Students frequently ask questions whose answers are missing from the documents, are "
      "split across documents, or have been changed by a newer circular.")
    P("Recent benchmarks show that LLMs inside RAG pipelines struggle exactly here: they rarely refuse when "
      "evidence is missing, integrate several documents poorly and are misled by false or conflicting context [1], "
      "[6], and they still produce claims unsupported by the retrieved text [8]. This project designs, implements "
      "and evaluates a verification layer that addresses these failure modes with free, CPU-friendly components.")

    H1("2. Problem Statement")
    P("Ordinary LLM systems may generate unsupported answers, hallucinate information or fail to recognise "
      "conflicting documents. The task is to build a university knowledge assistant that retrieves information "
      "from uploaded documents and verifies whether sufficient and consistent evidence exists before generating "
      "an answer, and to measure, against a standard RAG baseline, whether this verification reduces unsupported "
      "answers without unacceptable loss of helpfulness.")

    H1("3. Research Objectives")
    NUM(OBJECTIVES)
    P("Research questions. RQ1: Does evidence verification reduce unsupported answers compared with standard RAG? "
      "RQ2: Can inter-document conflicts in versioned university rules be detected with training-free components? "
      "RQ3: What is the cost of verification in over-abstention and latency? RQ4: How much do hybrid retrieval and "
      "reranking contribute on their own?")
    BR()

    # --------------------------------------------------------------- 4 literature
    H1("4. Literature Review")
    P("Papers were identified through targeted searches of AAAI, ICLR, NeurIPS, ACL Anthology and arXiv, and "
      "every bibliographic detail below was verified against the publisher or proceedings page. Eight papers "
      "from 2023-2024 were selected because each addresses one failure mode that EvidenceGuard targets.")
    for i, p in enumerate(PAPERS, 1):
        H2(f"4.{i} {p['title']} ({p['authors'].split(',')[0].split()[-1]} et al., {p['year']})")
        P(f"{p['venue']}. Problem: {p['problem']} Method: {p['method']} Technologies: {p['technologies']} "
          f"Results: {p['results']} Limitations: {p['limitations']}")
    H2("4.9 Literature review table")
    rows = [[f"[{i}] {p['title']} - {p['authors']} ({p['year']}), {p['venue']}",
             p["problem"] + " / " + p["method"], p["results"], p["limitations"], p["gap"], p["ours"]]
            for i, p in enumerate(PAPERS, 1)]
    TABLE(["Paper", "Problem / methodology", "Results", "Limitations", "Research gap", "How EvidenceGuard addresses it"],
          rows, widths=[2.6, 3.0, 2.4, 2.4, 2.2, 3.0], size=7)
    CAP("Table 1. Literature review (technologies are listed in Sections 4.1-4.8).")
    BR()

    H1("5. Research Gap")
    P(RESEARCH_GAP)
    P("Why this gap is realistic for a student project: all components are pre-trained and free (no fine-tuning), "
      "the corpus and benchmark are generated locally, and the full experiment runs on a laptop CPU.")

    # --------------------------------------------------------------- 6 methodology
    H1("6. Proposed Methodology")
    NUM(["Data creation: generate a fictional but internally consistent policy corpus with planted conflicts, "
         "superseding circulars, distractors and uncovered topics; derive 100 questions with gold evidence pages.",
         "Baseline (System A): PDF ingestion, cleaning, sentence-aware chunking, Sentence-Transformer embeddings, "
         "FAISS search, LLM generation with source citations.",
         "EvidenceGuard (System B): hybrid retrieval, cross-encoder reranking, sufficiency gate, conflict-search "
         "retrieval and contradiction detection, conflict-aware grounded generation, citation validation, "
         "confidence-based abstention and explanation.",
         f"Calibration: thresholds tuned by grid search on a stratified DEV split ({meta['dev_questions']} "
         f"questions) only; results reported on all 100 and on the {meta['test_questions']} held-out TEST questions.",
         "Ablation: (1) baseline, (2) + hybrid retrieval and reranking, (3) + verification without reranking, "
         "(4) complete EvidenceGuard; paired significance tests (exact McNemar, bootstrap 95% CI)."])

    H1("7. System Architecture")
    IMG(ROOT / "assets" / "architecture.png", 16.5)
    CAP("Figure 1. EvidenceGuard AI architecture (ingestion layer, System A, System B and user interface).")
    P("The code is modular (src/): document_processor (extraction, cleaning, chunking), embeddings, vector_store "
      "(FAISS + BM25 knowledge base), retrieval (dense, BM25, hybrid RRF), reranker, evidence_verifier, "
      "llm_generator, baseline_rag, enhanced_rag, evaluation and system (factory). Every Hugging Face component "
      "has an offline fallback selected automatically if the model cannot be loaded.")

    H1("8. Workflow Diagram")
    IMG(ROOT / "assets" / "workflow.png", 12.5)
    CAP("Figure 2. Decision workflow of EvidenceGuard: answered, partial, conflict warning or abstained.")
    BR()

    # --------------------------------------------------------------- 9 dataset
    H1("9. Dataset Creation Methodology")
    P("No external data was used. The script scripts/generate_dataset.py renders every document from a single "
      "Python fact base (scripts/corpus_content.py) with ReportLab, so facts are consistent by construction. "
      "Each page carries the banner 'SYNTHETIC DEMONSTRATION DATA - fictional university, not a real policy', a "
      "metadata table (document number, version, issue and effective dates) and page numbers.")
    TABLE(["ID", "Document", "Issued", "Pages", "Role in the benchmark"],
          [[d["id"], d["title"], d["issued"], str(len(d["pages"])), d["topic"]] for d in DOCUMENTS],
          widths=[1.0, 7.0, 2.2, 1.2, 4.6], size=7.5)
    CAP("Table 2. Synthetic document collection (Aranya Valley University is fictional).")
    P("Planted conflicts: minimum attendance 75% vs 80%; condonation limit 10% vs 5% and fee INR 500 vs INR 1,000; "
      "scholarship deadline 31 August vs 15 September 2025 and income ceiling INR 6,00,000 vs 8,00,000; late "
      "assignments accepted with a 10%/day penalty vs not accepted; PG borrowing 5 books/14 days/INR 5 fine vs "
      "6 books/21 days/INR 10; add/drop 10 vs 7 working days; PG pass mark 40% vs 50%; examinations starting "
      "1 vs 3 December 2025. A hostel guidelines document acts as a distractor full of look-alike numbers.")
    cats = Counter(q["category"] for q in QS)
    TABLE(["Category", "Questions", "Expected evidence status", "Expected behaviour"],
          [["Answerable", str(cats["answerable"]), "sufficient", "answer with citation"],
           ["Multi-passage", str(cats["multi_passage"]), "sufficient", "combine two passages / documents"],
           ["Missing information", str(cats["missing"]), "insufficient", "abstain"],
           ["Misleading / irrelevant context", str(cats["misleading"]), "sufficient", "correct a false premise or ignore distractors"],
           ["Conflicting", str(cats["conflicting"]), "conflicting", "flag the conflict and present both versions"]],
          widths=[4.0, 2.0, 3.6, 6.4], size=8)
    CAP("Table 3. Evaluation question set (evaluation_data/questions.json and .csv).")
    P("Each question stores the expected answer, the key facts a correct answer must contain, the supporting "
      "document(s) and page(s), the expected evidence status and the expected behaviour. The generator locates "
      "every evidence phrase in the extracted PDF text and refuses to write the dataset if a phrase or key fact "
      "is missing, which guarantees that questions are derived from the PDFs.")

    # --------------------------------------------------------------- 10 models
    H1("10. Model Selection")
    TABLE(["Role", "Hugging Face model (deployment)", "Why", "Offline fallback (used in reported run)"],
          [["Embeddings", "sentence-transformers/all-MiniLM-L6-v2 (384-d)", "Small, fast on CPU, strong general retrieval [10]",
            "LSA: TF-IDF (1-2 grams) + TruncatedSVD"],
           ["Vector DB", "FAISS IndexFlatIP", "Exact cosine search; corpus is small [11]", "same"],
           ["Keyword", "BM25 (rank_bm25) + RRF", "Exact terms such as 'condonation', codes, dates [12], [13]", "same"],
           ["Reranker", "cross-encoder/ms-marco-MiniLM-L-6-v2", "Joint query-passage scoring [14]", "Lexical cross-scorer (IDF coverage, bigrams, BM25)"],
           ["NLI", "cross-encoder/nli-deberta-v3-xsmall", "Contradiction/entailment probabilities; ~70M params", "Numeric-value and polarity rules"],
           ["LLM", "Qwen/Qwen2.5-0.5B-Instruct (local CPU) or HF Inference API (HF_TOKEN secret)",
            "Free, instruction-tuned, fits free CPU Space", "Extractive composer (no LLM)"]],
          widths=[2.0, 4.6, 4.6, 4.8], size=7.5)
    CAP("Table 4. Model selection. The model licences should be re-checked on each model card before deployment.")
    P("Constraints considered: free CPU Spaces (2 vCPU, 16 GB RAM) make 7B models impractical locally, so the "
      "default local LLM is a 0.5B model and a larger model can be used through the Hugging Face Inference API "
      "with a token stored as a Space secret. No API key is written in code. NLI models are known to be weak at "
      "comparing numbers, which dominate policy text, so contradiction detection always also runs explicit "
      "numeric-value rules.")
    BR()

    # --------------------------------------------------------------- 11 implementation
    H1("11. Implementation")
    H2("11.1 Ingestion and indexing")
    P("PyMuPDF extracts page text (pypdf fallback). Cleaning removes the synthetic-data banner and footers, "
      "de-hyphenates, and terminates short title-case headings so they do not merge with the next sentence. "
      "Pages are split into sentences and packed into ~70-word chunks with a one-sentence overlap; each chunk keeps "
      "its document, title, page and issue date. The knowledge base builds a FAISS index and a BM25 index and "
      "stores IDF weights used by the verifier. Uploaded PDFs are added (or replaced) at run time.")
    H2("11.2 Evidence sufficiency")
    P("The verifier extracts content words of the question (stop words and generic domain words removed, light "
      "stemming) and weights them by IDF; words that never occur in the corpus get the maximum weight. Coverage is "
      "the average of (a) the weighted share of question terms found in the best single passage and (b) the share "
      "found in the top three passages. Evidence is sufficient if the best passage relevance and the coverage "
      "both exceed calibrated thresholds; partial if slightly below and no question term is absent from the whole "
      "corpus; otherwise the system abstains and lists the missing terms.")
    H2("11.3 Conflict-search retrieval and contradiction detection")
    P("Competing versions of a rule are often outside the top-k (an amendment circular is short and worded "
      "differently). The verifier therefore re-queries the index with the best evidence sentences and adds "
      "passages from other documents as conflict candidates. Sentence pairs from different documents are then "
      "tested: (i) numeric conflict - the same kind of value (%, INR, days, books, dates...) with a different "
      "number, described by overlapping words, of the type the question asks about, where the question words near "
      "the value appear in both sentences and the values differ by less than 5x; (ii) polarity conflict - one "
      "sentence negates a predicate that the other asserts; (iii) NLI contradiction probability above a threshold "
      "(when the NLI model is available). The issue dates identify the newer document and update cues "
      "('revised to', 'supersedes', 'extended to') are reported.")
    H2("11.4 Generation, citation validation and abstention")
    P("The grounded prompt instructs the LLM to use only numbered passages, cite every sentence, reply "
      "INSUFFICIENT_EVIDENCE when the answer is absent, present both versions of conflicts and correct false "
      "premises. Every generated sentence is validated against its cited passage: all numbers must occur in the "
      "passage and token overlap must exceed a threshold, or the NLI model must predict entailment. Unsupported "
      "sentences are removed; if none remain the system abstains. Confidence = 0.4 x relevance + 0.4 x coverage "
      "+ 0.2 x supported-sentence ratio. Each response carries an explanation of the decision.")
    H2("11.5 Gradio application")
    P("Seven tabs: Home dashboard, Upload Documents, AI Assistant (chat with follow-up contextualisation and a "
      "Baseline/EvidenceGuard switch), Evidence Verification, Model Comparison, Evaluation Dashboard (with a "
      "button that re-runs the full evaluation) and About Project. Every button is wired to a working function; "
      "this was verified with 21 automated end-to-end interaction tests (Section 14).")
    for i, (fn, cap) in enumerate([("01_home.png", "Home dashboard with live technology stack"),
                                    ("03_assistant.png", "AI Assistant: abstention and an answer from a newly uploaded PDF"),
                                    ("04_verification.png", "Evidence Verification tab for a conflicting attendance question"),
                                    ("05_comparison.png", "Model Comparison: baseline answers an unanswerable question, EvidenceGuard abstains"),
                                    ("06_dashboard.png", "Evaluation Dashboard with real metrics")], 3):
        p = ROOT / "docs" / "screenshots" / fn
        if p.exists():
            IMG(p, 15.5)
            CAP(f"Figure {i}. {cap} (actual screenshot of the running application).")
    BR()

    # --------------------------------------------------------------- 12-13 experimental setup & metrics
    H1("12. Experimental Setup")
    comps = meta["components"]
    BUL([f"Hardware: {meta['cpu_count']} CPU cores ({meta['machine']}), no GPU; Python {meta['python']}.",
         f"Components actually used in the reported run: " + "; ".join(f"{k} = {v}" for k, v in comps.items()) + ".",
         "Reason: Hugging Face model downloads were blocked in the build environment. The Hugging Face path is "
         "implemented and was smoke-tested end-to-end with locally built miniature models, but its metrics must be "
         "produced by re-running scripts/run_evaluation.py --backend full (e.g. on Kaggle or the Space).",
         f"Split: stratified by category, seed 42: {meta['dev_questions']} DEV questions (threshold calibration only) "
         f"and {meta['test_questions']} TEST questions.",
         "Calibrated thresholds: " + ", ".join(f"{k} = {v}" for k, v in CAL["thresholds"].items()
                                                if k in ("min_relevance", "min_coverage", "partial_coverage", "min_confidence",
                                                         "conflict_sentence_coverage", "conflict_topic_sim")) + ".",
         "Top-k = 5 passages; 20 candidates per retriever before fusion/reranking; RRF k = 60.",
         f"Total runtime of calibration + 4 x 100 questions: {meta['runtime_s']} s."])

    H1("13. Evaluation Metrics")
    TABLE(["Group", "Metric", "Definition used"],
          [["Retrieval", "Precision@5 / Recall@5 / MRR", "Gold unit = (document, page) of the evidence; computed over the 85 questions with evidence"],
           ["Answer", "Answer correctness", "All key facts present (normalised match) for answerable questions; abstention for missing-information questions"],
           ["Answer", "Expected-behaviour accuracy", "Answer / abstain / flag conflict (with both values) / correct premise, as labelled"],
           ["Answer", "Faithfulness", "Share of answer sentences whose numbers and >=70% of tokens occur in the retrieved context"],
           ["Answer", "Evidence-grounded faithfulness", "Same check against the gold evidence pages only"],
           ["Answer", "Answer relevance", "TF-IDF cosine between question and answer (lexical proxy for RAGAS answer relevance)"],
           ["Answer", "Context precision / recall", "Rank-weighted AP@5 of gold pages / share of key facts present in the context"],
           ["Reliability", "Unsupported answer rate", "Non-abstaining answers to unanswerable questions or containing none of the key facts"],
           ["Reliability", "Abstention accuracy, P/R/F1", "Abstain decision vs. 'missing information' label"],
           ["Reliability", "Contradiction P/R/F1", "Conflict flag vs. 'conflicting' label"],
           ["Reliability", "Citation support accuracy", "Share of cited passages that are gold evidence pages"],
           ["Efficiency", "Response / retrieval / generation time", "Mean wall-clock seconds per question"]],
          widths=[2.2, 4.4, 9.4], size=7.5)
    CAP("Table 5. Metrics. Definitions follow RAGAS [7] and ALCE [4] but are computed deterministically against gold labels.")
    BR()

    # --------------------------------------------------------------- 14 results
    H1("14. Results")
    P(f"All numbers below are read from results/metrics.json (run of {meta['date']}). "
      "Experiments use synthetic documents of a fictional university and do not establish real-world accuracy.")
    keys = [("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)"), ("context_precision", "Context precision"),
            ("context_recall", "Context recall"), ("unsupported_answer_rate", "Unsupported answer rate (lower better)"),
            ("abstention_accuracy", "Abstention accuracy"), ("abstention_precision", "Abstention precision"),
            ("abstention_recall", "Abstention recall"), ("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 + rerank time (s)"),
            ("avg_verification_time_s", "Avg verification time (s)"), ("avg_generation_time_s", "Avg generation time (s)")]
    for split, label, tno in ((T, f"held-out TEST split ({meta['test_questions']} questions)", 6), (A, "all 100 questions", 7)):
        rows = [[lab] + [f(m(split, c, k), 4 if "time" in k else 3) for c in ORDER] for k, lab in keys]
        TABLE(["Metric"] + [NAMES[c] for c in ORDER], rows, widths=[5.6, 2.6, 2.6, 2.6, 2.6], size=8)
        CAP(f"Table {tno}. Four-configuration comparison on the {label}.")
    IMG(RES / "charts" / "reliability_comparison.png", 16)
    CAP("Figure 8. Reliability metrics (all 100 questions).")
    IMG(RES / "charts" / "answer_quality_comparison.png", 16)
    CAP("Figure 9. Answer quality metrics (all 100 questions).")
    IMG(RES / "charts" / "retrieval_comparison.png", 16)
    CAP("Figure 10. Retrieval metrics (all 100 questions).")
    IMG(RES / "charts" / "category_breakdown.png", 16)
    CAP("Figure 11. Expected-behaviour accuracy by question category.")
    IMG(RES / "charts" / "response_time.png", 15)
    CAP("Figure 12. Mean time per question.")
    H2("14.1 Statistical significance")
    TABLE(["Comparison (paired)", "Baseline", "EvidenceGuard", "Difference [95% CI]", "Discordant (EG only / base only)", "Exact McNemar p"],
          [[name, f"{s['baseline']:.3f}", f"{s['full']:.3f}", f"{s['difference']:+.3f} [{s['ci95'][0]:+.3f}, {s['ci95'][1]:+.3f}]",
            f"{s['only_other_true']} / {s['only_baseline_true']}", f"{s['mcnemar_exact_p']:.4f}"]
           for name, s in (("Behaviour accuracy - test", sig_b), ("Behaviour accuracy - all", sig_ba),
                           ("Unsupported answer - test", sig_u),
                           ("Unsupported answer - all", SIG["unsupported_answer|all|baseline_vs_full"]))],
          widths=[4.2, 1.8, 2.2, 3.4, 2.6, 1.8], size=7.5)
    CAP("Table 8. Paired significance tests, baseline vs. complete EvidenceGuard (results/significance.json).")
    rr = SIG["behaviour_accuracy|test|baseline_vs_rerank"]
    P(f"Reranking alone (configuration 2) did not change behaviour accuracy significantly "
      f"({rr['difference']:+.3f}, p = {rr['mcnemar_exact_p']:.2f}).")
    BR()

    # --------------------------------------------------------------- 15-16
    H1("15. Comparative Analysis")
    cb, cf = M["by_category"]["baseline"], M["by_category"]["full"]
    TABLE(["Category", "n", "Baseline behaviour acc.", "EvidenceGuard behaviour acc.", "Baseline abstention rate", "EvidenceGuard abstention rate"],
          [[c, str(cb[c]["n"]), f(cb[c]["behaviour_accuracy"]), f(cf[c]["behaviour_accuracy"]),
            f(cb[c]["abstention_rate"]), f(cf[c]["abstention_rate"])]
           for c in ["answerable", "multi_passage", "missing", "misleading", "conflicting"]],
          widths=[3.2, 1.0, 3.0, 3.2, 2.8, 2.8], size=8)
    CAP("Table 9. Per-category comparison (all 100 questions).")
    BUL([f"RQ1 - unsupported answers: the baseline answered every missing-information question "
         f"(behaviour accuracy {cb['missing']['behaviour_accuracy']:.2f}); EvidenceGuard abstained correctly on "
         f"{cf['missing']['behaviour_accuracy']:.0%} of them and lowered the overall unsupported-answer rate from "
         f"{m(A,'baseline','unsupported_answer_rate'):.2f} to {m(A,'full','unsupported_answer_rate'):.2f}.",
         f"RQ2 - conflicts: the baseline cannot flag conflicts (F1 = 0 by construction). EvidenceGuard reached "
         f"precision {m(A,'full','contradiction_precision'):.2f} and recall {m(A,'full','contradiction_recall'):.2f}; "
         f"the conflict-search retrieval step was needed for amendment circulars that were not in the top-5.",
         f"RQ3 - cost: answerable accuracy fell from {cb['answerable']['behaviour_accuracy']:.2f} to "
         f"{cf['answerable']['behaviour_accuracy']:.2f} and multi-passage from {cb['multi_passage']['behaviour_accuracy']:.2f} "
         f"to {cf['multi_passage']['behaviour_accuracy']:.2f} because of over-abstention; abstention precision is only "
         f"{m(A,'full','abstention_precision'):.2f}. Mean latency rose from {m(A,'baseline','avg_response_time_s')*1000:.1f} ms "
         f"to {m(A,'full','avg_response_time_s')*1000:.1f} ms with offline components (an LLM would dominate latency).",
         "RQ4 - retrieval: recall@5 was already high for the dense LSA baseline on this small corpus, so hybrid "
         "retrieval and the lexical reranker added little; the improvements come from the verification layer "
         "(configurations 3 and 4 are almost identical).",
         f"Note on abstention accuracy: the baseline's {m(A,'baseline','abstention_accuracy'):.2f} is the majority-class rate "
         "(it never abstains while 85% of questions are answerable); abstention F1 is the informative measure.",
         "Faithfulness to context is 1.0 for all configurations because the offline extractive composer can only copy "
         "retrieved sentences; evidence-grounded faithfulness shows the real difference (sentences taken from the right pages)."])
    IMG(RES / "charts" / "error_analysis.png", 16)
    CAP("Figure 13. Error taxonomy, baseline vs. EvidenceGuard (results/error_analysis.csv).")
    H2("15.1 Failure case examples")
    ex, seen_t = [], Counter()
    for e in FAIL["evidenceguard_failures"]:                 # diverse: at most 2 per error type
        if seen_t[e["error_type"]] < 2:
            ex.append(e)
            seen_t[e["error_type"]] += 1
    TABLE(["ID", "Question", "Error type", "EvidenceGuard output (truncated)"],
          [[e["id"], e["question"], e["error_type"], plain(e["answer"])[:220]] for e in ex],
          widths=[1.1, 5.0, 3.0, 6.9], size=7)
    CAP("Table 10. Examples of EvidenceGuard failures (full list in results/failure_cases.json).")
    wins, seen_c = [], Counter()
    for w in FAIL["evidenceguard_fixes_over_baseline"]:      # one or two per category
        if seen_c[w["category"]] < (2 if w["category"] == "conflicting" else 1):
            wins.append(w)
            seen_c[w["category"]] += 1
    TABLE(["ID", "Question", "Baseline answer", "EvidenceGuard answer"],
          [[w["id"], w["question"], plain(w["baseline_answer"])[:170], plain(w["evidenceguard_answer"])[:170]] for w in wins],
          widths=[1.1, 4.3, 5.3, 5.3], size=7)
    CAP("Table 11. Examples where EvidenceGuard corrected a baseline failure.")
    BR()

    H1("16. Discussion")
    P("The experiment supports the central claim within its scope: a training-free verification layer can stop a "
      "RAG assistant from answering questions its documents cannot support and can surface conflicting rule "
      "versions instead of silently choosing one. This matches the failure modes reported in RGB [1] and "
      "WikiContradict [6], and turns the post-hoc citation evaluation of ALCE [4] into an in-pipeline filter. The "
      "price is over-abstention, the same trade-off Yoran et al. [5] observed for NLI filtering: when a question "
      "is paraphrased away from the document wording, or needs two passages, coverage drops below the threshold. "
      "A practical deployment should therefore present abstentions as 'not found - please check with the office' "
      "with the retrieved passages visible, which the application does.")
    P("Two results temper the conclusions. First, the behaviour-accuracy gain partly reflects the benchmark design: "
      "conflict questions require a conflict flag that the baseline cannot produce. The unsupported-answer rate, "
      "which does not depend on that design, is the cleaner evidence and is also significant. Second, the rule "
      "components were designed while inspecting failures on the same question set; only thresholds were "
      "calibrated on the DEV split. The test results are therefore optimistic and should be confirmed on new, "
      "independently written questions and on real documents.")

    H1("17. Limitations")
    BUL(LIMITATIONS)
    H1("18. Future Enhancements")
    BUL(FUTURE)
    H1("19. Conclusion")
    P(f"EvidenceGuard AI demonstrates that evidence verification can be added to a RAG assistant with free, "
      f"CPU-only components. On a synthetic university benchmark it reduced unsupported answers by "
      f"{abs(sig_u['difference']):.1%} absolute on held-out questions, detected conflicting rule versions with F1 "
      f"{m(T,'full','contradiction_f1'):.2f}, and explained every decision, at the cost of some over-abstention. The "
      "complete system - data generator, two RAG systems, verification module, evaluation suite and seven-tab "
      "Gradio application - is reproducible from the repository and prepared for Hugging Face Spaces.")
    BR()

    # --------------------------------------------------------------- references
    H1("20. References")
    refs = [f"{p['authors']}, \"{p['title']},\" {p['venue']}, {p['year']}. [Online]. Available: {p['link']}"
            for p in PAPERS] + FOUNDATION
    B.append({"t": "refs", "items": refs})
    H1("Appendix A. Reproducing the results")
    CODE("pip install -r requirements.txt\npython scripts/generate_dataset.py      # 16 PDFs + 100 questions\n"
         "python scripts/run_evaluation.py --backend lite --llm extractive   # this report\n"
         "python scripts/run_evaluation.py --backend full --llm hf_api       # HF models (needs HF_TOKEN)\n"
         "python scripts/significance.py\npython -m pytest -q\npython app.py")


def readme_table():
    meta = M["meta"]
    keys = [("recall_at_k", "Recall@5"), ("mrr", "MRR"), ("answer_correctness", "Answer correctness"),
            ("behaviour_accuracy", "Expected-behaviour accuracy"), ("grounded_faithfulness", "Evidence-grounded faithfulness"),
            ("unsupported_answer_rate", "Unsupported answer rate ↓"), ("abstention_f1", "Abstention F1"),
            ("contradiction_f1", "Contradiction F1"), ("citation_support_accuracy", "Citation support accuracy"),
            ("avg_response_time_s", "Avg response time (s)")]
    lines = [f"Held-out TEST split ({meta['test_questions']} questions), backend `{meta['backend']}` "
             f"(offline fallback components), run {meta['date']}:\n",
             "| Metric | " + " | ".join(NAMES[c] for c in ORDER) + " |", "|---|" + "---|" * 4]
    for k, lab in keys:
        lines.append(f"| {lab} | " + " | ".join(f(m('test', c, k), 4 if 'time' in k else 3) for c in ORDER) + " |")
    sb, su = SIG["behaviour_accuracy|test|baseline_vs_full"], SIG["unsupported_answer|test|baseline_vs_full"]
    lines.append(f"\nPaired exact McNemar test, baseline vs EvidenceGuard (test split): behaviour accuracy "
                 f"{sb['difference']:+.3f} (p = {sb['mcnemar_exact_p']:.3f}); unsupported answers "
                 f"{su['difference']:+.3f} (p = {su['mcnemar_exact_p']:.3f}).")
    return "\n".join(lines)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--author", default="Leeshal Princia Monteiro")
    ap.add_argument("--usn", default="SCA25MSD042")
    ap.add_argument("--programme", default="MSc Data Science, School of Computer Applications")
    ap.add_argument("--institution", default="Dayananda Sagar University, Bengaluru")
    a = ap.parse_args()
    build(a.author, a.usn, a.programme, a.institution)
    out = ROOT / "reports"
    out.mkdir(exist_ok=True)
    (out / "report_model.json").write_text(json.dumps(B, indent=1))
    readme = ROOT / "README.md"
    if readme.exists():
        s = readme.read_text()
        if "<!-- RESULTS_START -->" in s:
            pre, rest = s.split("<!-- RESULTS_START -->", 1)
            post = rest.split("<!-- RESULTS_END -->", 1)[1]
            readme.write_text(pre + "<!-- RESULTS_START -->\n" + readme_table() + "\n<!-- RESULTS_END -->" + post)
    subprocess.run(["node", str(ROOT / "scripts" / "render_report_docx.js"), str(out / "report_model.json"),
                    str(out / "project_report.docx")], check=True)
    subprocess.run(["soffice", "--headless", "--convert-to", "pdf", "--outdir", str(out),
                    str(out / "project_report.docx")], check=True, capture_output=True)
    print("report written:", out / "project_report.docx", out / "project_report.pdf")


if __name__ == "__main__":
    main()