""" 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}|(?=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 "" in s: pre, rest = s.split("", 1) post = rest.split("", 1)[1] readme.write_text(pre + "\n" + readme_table() + "\n" + 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()