leeshal commited on
Commit
a805048
·
verified ·
1 Parent(s): 4f6c209

Upload 55 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. README.md +136 -5
  3. app.py +524 -0
  4. assets/architecture.png +3 -0
  5. assets/workflow.png +3 -0
  6. config.py +104 -0
  7. requirements.txt +19 -0
  8. results/calibrated_thresholds.json +51 -0
  9. results/category_breakdown.csv +21 -0
  10. results/charts/answer_quality_comparison.png +0 -0
  11. results/charts/category_breakdown.png +0 -0
  12. results/charts/error_analysis.png +0 -0
  13. results/charts/reliability_comparison.png +0 -0
  14. results/charts/response_time.png +0 -0
  15. results/charts/retrieval_comparison.png +0 -0
  16. results/error_analysis.csv +7 -0
  17. results/failure_cases.json +584 -0
  18. results/metrics.csv +13 -0
  19. results/metrics.json +537 -0
  20. results/per_question_results.csv +0 -0
  21. results/significance.json +158 -0
  22. scripts/build_report.py +492 -0
  23. scripts/corpus_content.py +618 -0
  24. scripts/generate_dataset.py +156 -0
  25. scripts/make_diagrams.py +130 -0
  26. scripts/questions_spec.py +334 -0
  27. scripts/render_report_docx.js +139 -0
  28. scripts/run_evaluation.py +316 -0
  29. scripts/significance.py +57 -0
  30. src/__init__.py +0 -0
  31. src/__pycache__/__init__.cpython-312.pyc +0 -0
  32. src/__pycache__/baseline_rag.cpython-312.pyc +0 -0
  33. src/__pycache__/document_processor.cpython-312.pyc +0 -0
  34. src/__pycache__/embeddings.cpython-312.pyc +0 -0
  35. src/__pycache__/enhanced_rag.cpython-312.pyc +0 -0
  36. src/__pycache__/evidence_verifier.cpython-312.pyc +0 -0
  37. src/__pycache__/llm_generator.cpython-312.pyc +0 -0
  38. src/__pycache__/reranker.cpython-312.pyc +0 -0
  39. src/__pycache__/research.cpython-312.pyc +0 -0
  40. src/__pycache__/retrieval.cpython-312.pyc +0 -0
  41. src/__pycache__/system.cpython-312.pyc +0 -0
  42. src/__pycache__/text_utils.cpython-312.pyc +0 -0
  43. src/__pycache__/vector_store.cpython-312.pyc +0 -0
  44. src/baseline_rag.py +60 -0
  45. src/document_processor.py +154 -0
  46. src/embeddings.py +71 -0
  47. src/enhanced_rag.py +174 -0
  48. src/evaluation.py +203 -0
  49. src/evidence_verifier.py +410 -0
  50. src/llm_generator.py +244 -0
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/architecture.png filter=lfs diff=lfs merge=lfs -text
37
+ assets/workflow.png filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,14 +1,145 @@
1
  ---
2
  title: EvidenceGuard AI
3
- emoji: 👁
4
  colorFrom: blue
5
- colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 6.32.0
8
- python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
11
- license: mit
 
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: EvidenceGuard AI
3
+ emoji: 🛡️
4
  colorFrom: blue
5
+ colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 6.32.0
8
+ python_version: "3.12"
9
  app_file: app.py
10
  pinned: false
11
+ license: apache-2.0
12
+ short_description: Evidence-verified RAG assistant for university rules
13
  ---
14
 
15
+ # 🛡️ EvidenceGuard AI – Your Verified University Knowledge Assistant
16
+
17
+ **A reliable university knowledge assistant using RAG, LLMs and evidence verification.**
18
+
19
+ Standard RAG chatbots answer *every* question, even when the documents do not contain the answer or when two
20
+ documents give different versions of the same rule. EvidenceGuard AI checks that **sufficient and consistent
21
+ evidence** exists before answering. Otherwise it gives a partial answer, shows both conflicting versions (and
22
+ names the newer document), or abstains and explains why.
23
+
24
+ > ⚠️ **All bundled documents are SYNTHETIC DEMONSTRATION DATA** describing *Aranya Valley University*, a
25
+ > fictional institution. They are not real university policies, and the experimental results do not establish
26
+ > real-world policy accuracy.
27
+
28
+ ## What's inside
29
+
30
+ | Path | Contents |
31
+ |---|---|
32
+ | `app.py` | 7-tab Gradio app (Home, Upload, AI Assistant, Evidence Verification, Model Comparison, Evaluation Dashboard, About) |
33
+ | `config.py` | Models, backends, thresholds (all overridable by environment variables / Space secrets) |
34
+ | `src/` | `document_processor`, `embeddings`, `vector_store`, `retrieval`, `reranker`, `evidence_verifier`, `llm_generator`, `baseline_rag`, `enhanced_rag`, `evaluation`, `system`, `research`, `text_utils` |
35
+ | `sample_data/` | 16 generated PDFs (28 pages) + `corpus_manifest.json` |
36
+ | `evaluation_data/` | `questions.json` / `questions.csv`: 100 questions with evidence document, page, status and behaviour |
37
+ | `results/` | `metrics.csv`, `metrics.json`, per-question results, category breakdown, error analysis, failure cases, significance tests, `charts/` |
38
+ | `reports/` | `project_report.pdf`, `project_report.docx` |
39
+ | `assets/` | `architecture.png`, `workflow.png` |
40
+ | `docs/` | `TEST_REPORT.md`, `screenshots/` |
41
+ | `scripts/` | dataset generator, evaluation runner, significance tests, diagram and report builders |
42
+ | `tests/` | pytest suite (20 tests) |
43
+
44
+ ## Two systems
45
+
46
+ **System A – Baseline RAG:** PDF ingestion → extraction → cleaning → chunking → Sentence-Transformer embeddings → FAISS → semantic retrieval → LLM answer → source citations.
47
+
48
+ **System B – EvidenceGuard RAG:** hybrid retrieval (FAISS + BM25 fused with reciprocal rank fusion) → cross-encoder reranking → **evidence-sufficiency check** → **conflict-search retrieval + contradiction detection** (NLI + numeric/polarity rules) → context-grounded, conflict-aware generation → **citation validation** of every sentence → **confidence-based abstention** → explanation (answered / partial / conflict / abstained).
49
+
50
+ ![architecture](assets/architecture.png)
51
+
52
+ ## Models (free, open licences – verify on each model card)
53
+
54
+ | Role | Default model | Offline fallback |
55
+ |---|---|---|
56
+ | Embeddings | `sentence-transformers/all-MiniLM-L6-v2` | LSA (TF-IDF + TruncatedSVD) |
57
+ | Reranker | `cross-encoder/ms-marco-MiniLM-L-6-v2` | lexical cross-scorer |
58
+ | NLI | `cross-encoder/nli-deberta-v3-xsmall` | numeric-value & polarity rules |
59
+ | LLM (local CPU) | `Qwen/Qwen2.5-0.5B-Instruct` | extractive composer (no LLM) |
60
+ | LLM (API, optional) | `Qwen/Qwen2.5-7B-Instruct` via HF Inference Providers (`HF_TOKEN`) | – |
61
+
62
+ `EG_BACKEND=auto` (default) loads the Hugging Face models and falls back component-by-component if one cannot
63
+ be loaded. `EG_BACKEND=lite` forces the offline components (fast, no downloads).
64
+
65
+ ## Run locally
66
+
67
+ ```bash
68
+ python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
69
+ pip install -r requirements.txt
70
+ python app.py # http://127.0.0.1:7860
71
+ ```
72
+
73
+ Fully offline / fastest start: `EG_BACKEND=lite LLM_BACKEND=extractive python app.py`
74
+
75
+ Regenerate everything:
76
+
77
+ ```bash
78
+ python scripts/generate_dataset.py # PDFs + 100 questions
79
+ python scripts/run_evaluation.py --backend lite --llm extractive # results/ + charts (≈25 s on CPU)
80
+ python scripts/significance.py # McNemar + bootstrap CIs
81
+ python scripts/make_diagrams.py # assets/*.png
82
+ pip install -r requirements-dev.txt && python -m pytest -q # tests
83
+ python scripts/build_report.py # reports/*.docx + *.pdf (needs Node `docx` + LibreOffice)
84
+ ```
85
+
86
+ With the Hugging Face model stack (e.g. on Kaggle/Colab or the Space):
87
+ `python scripts/run_evaluation.py --backend full --llm local` (or `--llm hf_api` with `HF_TOKEN` set). Thresholds
88
+ are re-calibrated on the DEV split for that backend automatically.
89
+
90
+ ## Results (real, from `results/metrics.json`)
91
+
92
+ <!-- RESULTS_START -->
93
+ Held-out TEST split (71 questions), backend `lite` (offline fallback components), run 2026-11-19 07:51:
94
+
95
+ | Metric | Baseline RAG | + Reranking | + Verification | EvidenceGuard |
96
+ |---|---|---|---|---|
97
+ | Recall@5 | 0.975 | 0.992 | 0.983 | 0.992 |
98
+ | MRR | 0.975 | 0.958 | 0.975 | 0.958 |
99
+ | Answer correctness | 0.563 | 0.549 | 0.704 | 0.704 |
100
+ | Expected-behaviour accuracy | 0.535 | 0.521 | 0.704 | 0.704 |
101
+ | Evidence-grounded faithfulness | 0.770 | 0.747 | 0.858 | 0.844 |
102
+ | Unsupported answer rate ↓ | 0.211 | 0.225 | 0.099 | 0.099 |
103
+ | Abstention F1 | 0.000 | 0.000 | 0.588 | 0.588 |
104
+ | Contradiction F1 | 0.000 | 0.000 | 0.720 | 0.720 |
105
+ | Citation support accuracy | 0.756 | 0.730 | 0.826 | 0.812 |
106
+ | Avg response time (s) | 0.0014 | 0.0023 | 0.0040 | 0.0052 |
107
+
108
+ Paired exact McNemar test, baseline vs EvidenceGuard (test split): behaviour accuracy +0.169 (p = 0.029); unsupported answers -0.113 (p = 0.039).
109
+ <!-- RESULTS_END -->
110
+
111
+ **Read these honestly:** gains come from the verification layer. Reranking alone gave no improvement on this
112
+ small corpus. EvidenceGuard over-abstains on some answerable multi-part questions. The reported run used the
113
+ **offline fallback components**, because Hugging Face downloads were blocked in the build environment; re-run with
114
+ `--backend full` to measure the Hugging Face model stack. The verification rules were developed on the same
115
+ question set (only thresholds were calibrated on the DEV split), so the test numbers are optimistic.
116
+
117
+ ## Deploy to Hugging Face Spaces
118
+
119
+ 1. Create a Space at <https://huggingface.co/new-space>: SDK **Gradio**, hardware **CPU basic (free)**.
120
+ 2. Push this repository to it:
121
+ ```bash
122
+ git remote add space https://huggingface.co/spaces/<your-username>/EvidenceGuard-AI
123
+ git push space main
124
+ ```
125
+ (Authenticate with a Hugging Face **write** token as the password, or use `huggingface-cli login`.)
126
+ PDFs and PNGs are binary: if the push is rejected, run `git lfs install && git lfs track "*.pdf" "*.png"` and commit again.
127
+ 3. Optional **Settings → Variables and secrets**:
128
+ - `HF_TOKEN` (secret) – enables the stronger LLM through Hugging Face Inference Providers
129
+ - `LLM_BACKEND` = `hf_api` | `local` | `extractive` (default `auto`)
130
+ - `EG_BACKEND` = `auto` | `full` | `lite`
131
+ 4. The first start downloads ~0.1 GB of encoder models (+ ~1 GB if the local Qwen LLM is used), which takes a few minutes.
132
+ Sample data is in the repository, so it is reloaded on every restart.
133
+
134
+ Never commit tokens; `config.py` reads credentials only from environment variables.
135
+
136
+ ## Research basis (verified)
137
+
138
+ Chen et al. (AAAI 2024, RGB) · Asai et al. (ICLR 2024, Self-RAG) · Yan et al. (arXiv 2024, CRAG) ·
139
+ Gao et al. (EMNLP 2023, ALCE) · Yoran et al. (ICLR 2024) · Hou et al. (NeurIPS 2024 D&B, WikiContradict) ·
140
+ Es et al. (EACL 2024 demos, RAGAS) · Niu et al. (ACL 2024, RAGTruth). Full table and IEEE references are in the report
141
+ and in the app's About tab.
142
+
143
+ ## Licence
144
+
145
+ Code: Apache-2.0. Generated documents and questions: synthetic, free to reuse with the "synthetic" label kept.
app.py ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ EvidenceGuard AI - Your Verified University Knowledge Assistant
3
+ Gradio application (entry point for local runs and Hugging Face Spaces).
4
+
5
+ python app.py -> http://127.0.0.1:7860
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import logging
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+ import threading
16
+ from pathlib import Path
17
+
18
+ import gradio as gr
19
+ import pandas as pd
20
+
21
+ import config
22
+ from src.research import FOUNDATION, FUTURE, LIMITATIONS, OBJECTIVES, PAPERS, RESEARCH_GAP
23
+ from src.system import CONFIG_NAMES, EvidenceGuardSystem
24
+
25
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
26
+ log = logging.getLogger("app")
27
+
28
+ SYSTEM = EvidenceGuardSystem() # loads models (or fallbacks) + the synthetic sample corpus
29
+ LOCK = threading.Lock() # uploads rebuild the shared index
30
+ ASSETS = config.ROOT / "assets"
31
+
32
+ EXAMPLES = [
33
+ "What is the minimum attendance required to appear for end-semester examinations?",
34
+ "How many books can a postgraduate student borrow from the library?",
35
+ "What is the fee for revaluation of answer scripts?",
36
+ "Given that internal assessment carries 50 marks, how many marks does the end-semester examination carry?",
37
+ "What is the late fee for course registration?",
38
+ "Are late assignment submissions accepted?",
39
+ "When is Internal Test 1 held this semester, and what must a student do to take a make-up test if they miss it through illness?",
40
+ ]
41
+
42
+ DECISION_BADGE = {
43
+ "answered": "✅ Answered - evidence verified",
44
+ "partial": "🟡 Partially answered - some parts not covered",
45
+ "conflict": "⚠️ Conflicting evidence - both versions shown",
46
+ "abstained": "⛔ Abstained - insufficient evidence",
47
+ }
48
+
49
+ # ============================================================================ helpers
50
+
51
+ def kb_table() -> pd.DataFrame:
52
+ rows = [{"Document": d.doc_name, "Title": d.title, "Issued": d.issued or "-", "Pages": d.pages,
53
+ "Chunks": d.chunks, "Status": d.status} for d in SYSTEM.kb.docs.values()]
54
+ return pd.DataFrame(rows, columns=["Document", "Title", "Issued", "Pages", "Chunks", "Status"])
55
+
56
+
57
+ def kb_summary() -> str:
58
+ n_docs, n_chunks = len(SYSTEM.kb.docs), len(SYSTEM.kb.chunks)
59
+ pages = sum(d.pages for d in SYSTEM.kb.docs.values())
60
+ return f"**Knowledge base:** {n_docs} documents · {pages} pages · {n_chunks} chunks indexed in FAISS + BM25."
61
+
62
+
63
+ def msg_text(m) -> str:
64
+ """Gradio 6 returns message content either as a string or as a list of typed parts."""
65
+ c = m.get("content") if isinstance(m, dict) else m
66
+ if isinstance(c, str):
67
+ return c
68
+ if isinstance(c, dict):
69
+ return c.get("text", "")
70
+ if isinstance(c, (list, tuple)):
71
+ return " ".join(msg_text({"content": x}) for x in c)
72
+ return str(c or "")
73
+
74
+
75
+ def contextualize(question: str, history: list) -> str:
76
+ """Follow-up support: short / referential questions inherit the previous user question."""
77
+ prev = [msg_text(m) for m in history if isinstance(m, dict) and m.get("role") == "user"]
78
+ if not prev:
79
+ return question
80
+ q = question.strip()
81
+ referential = re.match(r"^(and|what about|how about|also|then)\b", q, re.I) or \
82
+ re.search(r"\b(it|that|this|those|them|they|same)\b", q, re.I)
83
+ if referential or len(q.split()) <= 5:
84
+ last = prev[-1]
85
+ last = last.split("\n(Interpreted as:")[0]
86
+ return f"{q} (context: {last})"
87
+ return question
88
+
89
+
90
+ def citations_md(res: dict) -> str:
91
+ if not res.get("citations"):
92
+ return ""
93
+ lines = [f"[{c['n']}] {c['title']} - *{c['doc_name']}*, page {c['page']}" for c in res["citations"]]
94
+ return "\n\n**Sources:**\n" + "\n".join(f"- {x}" for x in lines)
95
+
96
+
97
+ def answer_md(res: dict, show_badge: bool = True) -> str:
98
+ label = DECISION_BADGE.get(res["decision"], res["decision"])
99
+ if res.get("sufficiency") is None and res["decision"] == "answered":
100
+ label = "ℹ️ Answered without verification (baseline - may be unsupported)"
101
+ badge = f"**{label}**\n\n" if show_badge else ""
102
+ conf = f"\n\n<sub>Confidence: {res['confidence']:.2f} · {res['explanation']}</sub>" \
103
+ if res.get("confidence") is not None else f"\n\n<sub>{res['explanation']}</sub>"
104
+ return badge + res["answer"] + citations_md(res) + conf
105
+
106
+
107
+ def passages_df(res: dict) -> pd.DataFrame:
108
+ rows = []
109
+ for p in res.get("passages", []):
110
+ rows.append({"#": p["n"], "Document": p["title"], "File": p["doc_name"], "Page": p["page"],
111
+ "Retrieval relevance": p["relevance"], "Dense": p["dense"], "BM25": p["sparse"],
112
+ "Source": p.get("source", "retrieval"),
113
+ "Passage": p["text"][:400] + ("..." if len(p["text"]) > 400 else "")})
114
+ return pd.DataFrame(rows)
115
+
116
+
117
+ def verification_md(res: dict | None) -> str:
118
+ if not res:
119
+ return "*Ask a question in the AI Assistant tab (or below) to see its evidence report here.*"
120
+ out = [f"### Question\n{res['question']}",
121
+ f"### Decision\n**{DECISION_BADGE.get(res['decision'], res['decision'])}**",
122
+ f"**Why:** {res['explanation']}"]
123
+ s = res.get("sufficiency")
124
+ if s:
125
+ out.append("### Evidence sufficiency\n"
126
+ f"| Signal | Value | Threshold |\n|---|---|---|\n"
127
+ f"| Best passage relevance | {s['max_relevance']:.3f} | {SYSTEM.verifier.th['min_relevance']:.2f} |\n"
128
+ f"| Query coverage (combined) | {s['coverage']:.3f} | {SYSTEM.verifier.th['min_coverage']:.2f} |\n"
129
+ f"| Coverage by best single passage | {s['coverage_single']:.3f} | - |\n"
130
+ f"| Coverage by top-3 passages | {s['coverage_union']:.3f} | - |\n"
131
+ f"| Status | **{s['status']}** | - |\n\n"
132
+ + (f"Question terms not found in evidence: `{', '.join(s['missing_terms'])}`"
133
+ if s["missing_terms"] else "All question terms found in the evidence."))
134
+ elif res["system"].startswith("1.") or res["system"].startswith("2."):
135
+ out.append("*Baseline configuration: no sufficiency, contradiction or citation checks are performed.*")
136
+ cs = res.get("conflicts") or []
137
+ out.append("### Contradiction status\n" + ("No contradiction detected between the retrieved documents."
138
+ if not cs else ""))
139
+ for c in cs:
140
+ out.append(f"- **{c['kind']} conflict** ({c['detail']})\n"
141
+ f" - *{c['title_a']}* (p.{c['page_a']}, issued {c['issued_a'] or '?'}): {c['sentence_a']}\n"
142
+ f" - *{c['title_b']}* (p.{c['page_b']}, issued {c['issued_b'] or '?'}): {c['sentence_b']}\n"
143
+ f" - Newer document: **{c['newer'] or 'unknown'}**"
144
+ + (" (explicitly revises the earlier rule)" if c["explicit_update"] else ""))
145
+ if res.get("premise_notes"):
146
+ out.append("### False-premise check\n" + "\n".join(f"- {p}" for p in res["premise_notes"]))
147
+ ch = res.get("citation_checks") or []
148
+ if ch:
149
+ out.append("### Citation verification\n| Sentence | Cited | Supported | Score | Reason |\n|---|---|---|---|---|\n" +
150
+ "\n".join(f"| {c['sentence'][:110].replace('|', '/')} | {c['cited']} | "
151
+ f"{'✅' if c['supported'] else '❌'} | {c['score']:.2f} | {c['reason'][:80]} |" for c in ch))
152
+ t = res["timings"]
153
+ out.append(f"### Timing\nretrieval {t['retrieval']*1000:.0f} ms · rerank {t.get('rerank', 0)*1000:.0f} ms · "
154
+ f"verification {t.get('verification', 0)*1000:.0f} ms · generation {t['generation']*1000:.0f} ms · "
155
+ f"**total {t['total']*1000:.0f} ms** · generator: {res.get('generator') or '-'}")
156
+ return "\n\n".join(out)
157
+
158
+
159
+ # ============================================================================ callbacks
160
+
161
+ def process_uploads(files):
162
+ if not files:
163
+ return pd.DataFrame(), kb_table(), kb_summary(), "Please choose one or more PDF files first."
164
+ paths = []
165
+ for f in files:
166
+ src = Path(f if isinstance(f, str) else f.name)
167
+ if src.suffix.lower() != ".pdf":
168
+ continue
169
+ dst = config.UPLOAD_DIR / src.name
170
+ shutil.copy(src, dst)
171
+ paths.append(dst)
172
+ if not paths:
173
+ return pd.DataFrame(), kb_table(), kb_summary(), "No PDF files were found in the upload."
174
+ with LOCK:
175
+ infos = SYSTEM.kb.add_pdfs(paths)
176
+ rows = [{"File": i.doc_name, "Extraction status": f"{i.status}: {i.message}", "Pages": i.pages,
177
+ "Chunks": i.chunks, "Detected title": i.title, "Detected date": i.issued or "-"} for i in infos]
178
+ ok = sum(i.status == "ok" for i in infos)
179
+ return (pd.DataFrame(rows), kb_table(), kb_summary(),
180
+ f"Processed {len(infos)} file(s): {ok} indexed successfully. You can now ask questions about them.")
181
+
182
+
183
+ def reset_kb():
184
+ with LOCK:
185
+ for d in list(SYSTEM.kb.docs):
186
+ SYSTEM.kb.docs.pop(d)
187
+ SYSTEM.kb.chunks = []
188
+ SYSTEM.kb.load_folder(config.SAMPLE_DATA_DIR)
189
+ return pd.DataFrame(), kb_table(), kb_summary(), "Knowledge base reset to the 16 synthetic sample documents."
190
+
191
+
192
+ def remove_doc(name):
193
+ with LOCK:
194
+ for did, d in list(SYSTEM.kb.docs.items()):
195
+ if d.doc_name == name:
196
+ SYSTEM.kb.remove_doc(did)
197
+ return kb_table(), kb_summary(), f"Removed {name}."
198
+ return kb_table(), kb_summary(), f"Document '{name}' not found."
199
+
200
+
201
+ def chat(message, history, mode):
202
+ history = history or []
203
+ if not message or not message.strip():
204
+ return history, "", None
205
+ if not SYSTEM.kb.ready:
206
+ history += [{"role": "user", "content": message},
207
+ {"role": "assistant", "content": "The knowledge base is empty. Upload PDFs in the Upload tab first."}]
208
+ return history, "", None
209
+ q = contextualize(message, history)
210
+ key = "full" if mode.startswith("EvidenceGuard") else "baseline"
211
+ with LOCK:
212
+ res = SYSTEM.pipelines[key].answer(q)
213
+ shown = message if q == message else f"{message}\n(Interpreted as: {q})"
214
+ history += [{"role": "user", "content": shown}, {"role": "assistant", "content": answer_md(res)}]
215
+ return history, "", res
216
+
217
+
218
+ def verify_direct(question, cfg):
219
+ if not question.strip():
220
+ return "Please type a question.", pd.DataFrame(), None
221
+ key = {v: k for k, v in CONFIG_NAMES.items()}[cfg]
222
+ with LOCK:
223
+ res = SYSTEM.pipelines[key].answer(question)
224
+ return verification_md(res), passages_df(res), res
225
+
226
+
227
+ def show_last(res):
228
+ return verification_md(res), passages_df(res) if res else pd.DataFrame()
229
+
230
+
231
+ def compare(question):
232
+ if not question.strip():
233
+ empty = "Please type a question."
234
+ return empty, empty, pd.DataFrame(), pd.DataFrame(), pd.DataFrame()
235
+ with LOCK:
236
+ a = SYSTEM.pipelines["baseline"].answer(question)
237
+ b = SYSTEM.pipelines["full"].answer(question)
238
+
239
+ def perf(r, name):
240
+ t = r["timings"]
241
+ return {"System": name, "Decision": r["decision"], "Passages": len(r["passages"]),
242
+ "Citations": len(r["citations"]), "Conflicts flagged": len(r.get("conflicts") or []),
243
+ "Confidence": r.get("confidence"), "Retrieval ms": round((t["retrieval"] + t.get("rerank", 0)) * 1000, 1),
244
+ "Verification ms": round(t.get("verification", 0) * 1000, 1),
245
+ "Generation ms": round(t["generation"] * 1000, 1), "Total ms": round(t["total"] * 1000, 1)}
246
+ perf_df = pd.DataFrame([perf(a, "Baseline RAG"), perf(b, "EvidenceGuard")])
247
+ return answer_md(a, show_badge=False), answer_md(b), passages_df(a), passages_df(b), perf_df
248
+
249
+
250
+ # ---------------------------------------------------------------------------- evaluation dashboard
251
+ METRIC_LABELS = {
252
+ "precision_at_k": "Precision@5", "recall_at_k": "Recall@5", "mrr": "MRR",
253
+ "answer_correctness": "Answer correctness", "behaviour_accuracy": "Expected-behaviour accuracy",
254
+ "faithfulness": "Faithfulness (to context)", "grounded_faithfulness": "Evidence-grounded faithfulness",
255
+ "answer_relevance": "Answer relevance (lexical proxy)", "context_precision": "Context precision (AP@5)",
256
+ "context_recall": "Context recall (key facts in context)", "unsupported_answer_rate": "Unsupported answer rate ↓",
257
+ "abstention_accuracy": "Abstention accuracy", "abstention_f1": "Abstention F1",
258
+ "contradiction_precision": "Contradiction precision", "contradiction_recall": "Contradiction recall",
259
+ "contradiction_f1": "Contradiction F1", "citation_support_accuracy": "Citation support accuracy",
260
+ "avg_response_time_s": "Avg response time (s)", "avg_retrieval_time_s": "Avg retrieval time (s)",
261
+ "avg_generation_time_s": "Avg generation time (s)", "avg_verification_time_s": "Avg verification time (s)",
262
+ }
263
+
264
+
265
+ def load_eval(split="all"):
266
+ p = config.RESULTS_DIR / "metrics.json"
267
+ if not p.exists():
268
+ return pd.DataFrame({"info": ["No results yet - click 'Re-run evaluation'."]}), "", pd.DataFrame(), pd.DataFrame(), pd.DataFrame()
269
+ m = json.loads(p.read_text())
270
+ names = m["config_names"]
271
+ order = ["baseline", "rerank", "verify", "full"]
272
+ rows = []
273
+ for k, lab in METRIC_LABELS.items():
274
+ rows.append({"Metric": lab, **{names[c]: m["metrics"][split][c].get(k) for c in order}})
275
+ meta = m["meta"]
276
+ info = (f"**Run:** {meta['date']} · {meta['n_questions']} questions ({meta['dev_questions']} dev used for "
277
+ f"threshold calibration, {meta['test_questions']} held-out test) · backend `{meta['backend']}` · "
278
+ f"runtime {meta['runtime_s']} s\n\n**Components used in this run:** " +
279
+ "; ".join(f"{k}: {v}" for k, v in meta["components"].items()) +
280
+ f"\n\n> ⚠️ {meta['note']}")
281
+ cat = pd.read_csv(config.RESULTS_DIR / "category_breakdown.csv")
282
+ err = pd.read_csv(config.RESULTS_DIR / "error_analysis.csv")
283
+ fails = json.loads((config.RESULTS_DIR / "failure_cases.json").read_text())
284
+ fdf = pd.DataFrame(fails["evidenceguard_failures"])[["id", "category", "question", "error_type", "answer",
285
+ "expected_answer", "explanation"]] \
286
+ if fails["evidenceguard_failures"] else pd.DataFrame()
287
+ return pd.DataFrame(rows), info, cat, err, fdf
288
+
289
+
290
+ def chart_paths():
291
+ names = ["retrieval_comparison", "answer_quality_comparison", "reliability_comparison",
292
+ "category_breakdown", "error_analysis", "response_time"]
293
+ return [str(config.CHARTS_DIR / f"{n}.png") if (config.CHARTS_DIR / f"{n}.png").exists() else None for n in names]
294
+
295
+
296
+ def rerun_eval(split):
297
+ backend = SYSTEM.effective_backend
298
+ cmd = [sys.executable, str(config.ROOT / "scripts" / "run_evaluation.py"), "--backend", backend,
299
+ "--llm", "extractive" if SYSTEM.generator.llm is None else config.LLM_BACKEND]
300
+ proc = subprocess.run(cmd, capture_output=True, text=True, cwd=str(config.ROOT), timeout=3600)
301
+ status = ("✅ Evaluation finished." if proc.returncode == 0 else "❌ Evaluation failed:\n" + proc.stderr[-1500:])
302
+ if proc.returncode == 0:
303
+ SYSTEM.set_thresholds(config.load_thresholds(SYSTEM.effective_backend))
304
+ return (status + "\n\n```\n" + proc.stdout[-1800:] + "\n```", *load_eval(split), *chart_paths())
305
+
306
+
307
+ # ============================================================================ UI text
308
+ HOME_MD = f"""
309
+ # 🛡️ EvidenceGuard AI
310
+ ### Your Verified University Knowledge Assistant
311
+
312
+ **Problem.** Ordinary LLM chatbots and standard RAG systems answer *every* question, even when the
313
+ documents do not contain the answer, when the retrieved text is irrelevant, or when two documents give
314
+ **different versions of the same rule** (e.g. an old regulation and a newer amendment circular).
315
+ For students, a confident wrong answer about attendance, exam eligibility or scholarship deadlines has real consequences.
316
+
317
+ **EvidenceGuard AI** retrieves information from university documents and **verifies that sufficient,
318
+ consistent evidence exists before answering**. Otherwise it gives a partial answer, shows both
319
+ conflicting versions, or refuses and explains why.
320
+
321
+ #### Key features
322
+ - 📄 Upload any PDFs; text extraction, cleaning, chunking and indexing (FAISS + BM25)
323
+ - 🔎 Hybrid semantic + keyword retrieval with cross-encoder reranking
324
+ - 🧪 Evidence-sufficiency check → **abstains** instead of guessing
325
+ - ⚖️ **Conflict search**: detects contradictions between documents and names the newer version
326
+ - 🔗 **Citation validation**: every answer sentence is checked against the passage it cites
327
+ - 💬 Explanations of why the system answered, partially answered or refused
328
+ - 📊 Side-by-side Baseline vs EvidenceGuard comparison and a real evaluation dashboard
329
+
330
+ #### Research contribution
331
+ A training-free, CPU-only verification layer combining sufficiency-based abstention, numeric-aware
332
+ inter-document contradiction detection with *conflict-search retrieval*, and inference-time citation
333
+ validation, evaluated with a 4-configuration ablation on a 100-question benchmark containing labelled
334
+ missing, misleading and conflicting questions.
335
+
336
+ > ⚠️ The bundled documents describe **Aranya Valley University, a fictional institution**. They are
337
+ > SYNTHETIC DEMONSTRATION DATA, not real university policy.
338
+ """
339
+
340
+ ABOUT_PARTS = []
341
+
342
+
343
+ def about_md():
344
+ lit = "| # | Paper | Authors (year) | Venue | Problem | Method | Limitation | How EvidenceGuard responds |\n|---|---|---|---|---|---|---|---|\n"
345
+ for i, p in enumerate(PAPERS, 1):
346
+ lit += (f"| {i} | [{p['title']}]({p['link']}) | {p['authors']} ({p['year']}) | {p['venue']} | {p['problem']} | "
347
+ f"{p['method']} | {p['limitations']} | {p['ours']} |\n")
348
+ refs = "\n".join(f"{i}. {p['authors']}, \"{p['title']},\" {p['venue']}. {p['link']}" for i, p in enumerate(PAPERS, 1))
349
+ refs += "\n" + "\n".join(f"{len(PAPERS) + i}. {r}" for i, r in enumerate(FOUNDATION, 1))
350
+ return f"""
351
+ ## Research papers (verified, 2023-2024)
352
+ {lit}
353
+
354
+ ## Research gap
355
+ {RESEARCH_GAP}
356
+
357
+ ## Objectives
358
+ {chr(10).join(f'{i}. {o}' for i, o in enumerate(OBJECTIVES, 1))}
359
+
360
+ ## Methodology
361
+ 1. **Synthetic corpus** - 16 fictional AVU PDFs (28 pages) generated from one fact base, with 9 planted conflicts,
362
+ superseding circulars, a distractor document and deliberately uncovered topics.
363
+ 2. **Benchmark** - 100 questions (30 answerable, 20 multi-passage, 15 missing-information, 15 misleading, 20 conflicting),
364
+ each with expected answer, key facts, evidence document/page, expected evidence status and behaviour.
365
+ 3. **Systems** - Baseline RAG (dense FAISS → LLM → citations) vs EvidenceGuard (hybrid → rerank → sufficiency →
366
+ conflict search & contradiction → grounded generation → citation validation → confidence/abstention).
367
+ 4. **Ablation** - 4 configurations; thresholds calibrated on a stratified DEV split (29 questions) only, results reported
368
+ on all 100 and on the 71 held-out TEST questions.
369
+ 5. **Metrics** - Precision/Recall@5, MRR, answer correctness, faithfulness, answer relevance, context precision/recall,
370
+ unsupported-answer rate, abstention and contradiction P/R/F1, citation support accuracy, latency.
371
+
372
+ ## Architecture
373
+ See the diagrams below. Every model component has an offline fallback so the app runs on any CPU.
374
+
375
+ ## Limitations
376
+ {chr(10).join(f'- {x}' for x in LIMITATIONS)}
377
+
378
+ ## Future scope
379
+ {chr(10).join(f'- {x}' for x in FUTURE)}
380
+
381
+ ## References (IEEE style)
382
+ {refs}
383
+ """
384
+
385
+
386
+ def stack_md():
387
+ rows = "\n".join(f"| {k} | {v} |" for k, v in SYSTEM.component_names().items())
388
+ return ("#### Technology stack (live - what this running instance is using)\n| Component | Implementation |\n|---|---|\n"
389
+ + rows + "\n| UI | Gradio |\n| PDF processing | PyMuPDF (pypdf fallback) |\n\n"
390
+ "If a Hugging Face model cannot be downloaded, the app automatically uses the offline fallback shown here.")
391
+
392
+
393
+ CSS = """
394
+ .gradio-container {max-width: 1280px !important}
395
+ .badge {font-size: 0.9em}
396
+ footer {visibility: hidden}
397
+ """
398
+
399
+ # ============================================================================ layout
400
+ with gr.Blocks(title="EvidenceGuard AI") as demo:
401
+ last_result = gr.State(None)
402
+ gr.Markdown("<h2 style='margin:0'>🛡️ EvidenceGuard AI - Your Verified University Knowledge Assistant</h2>"
403
+ "<span style='color:#b00020;font-size:0.85em'>Demo corpus = SYNTHETIC DEMONSTRATION DATA of a fictional university</span>")
404
+
405
+ # ---------------------------------------------------------------- TAB 1
406
+ with gr.Tab("🏠 Home"):
407
+ with gr.Row():
408
+ with gr.Column(scale=3):
409
+ gr.Markdown(HOME_MD)
410
+ with gr.Column(scale=2):
411
+ gr.Markdown(stack_md())
412
+ home_kb = gr.Markdown(kb_summary())
413
+ gr.Markdown("#### System workflow")
414
+ gr.Image(str(ASSETS / "workflow.png"), show_label=False, height=620)
415
+
416
+ # ---------------------------------------------------------------- TAB 2
417
+ with gr.Tab("📄 Upload Documents"):
418
+ gr.Markdown("Upload one or more PDFs. They are extracted, cleaned, chunked and added to the FAISS + BM25 index "
419
+ "alongside the sample documents. Re-uploading a file with the same name replaces it.")
420
+ with gr.Row():
421
+ up_files = gr.File(label="PDF files", file_count="multiple", file_types=[".pdf"])
422
+ with gr.Column():
423
+ up_btn = gr.Button("⚙️ Process documents into the vector database", variant="primary")
424
+ reset_btn = gr.Button("↩️ Reset to sample data")
425
+ up_status = gr.Markdown()
426
+ up_result = gr.Dataframe(label="Processing result (this upload)", interactive=False)
427
+ up_kb_md = gr.Markdown(kb_summary())
428
+ up_kb = gr.Dataframe(value=kb_table(), label="Documents in the knowledge base", interactive=False)
429
+ with gr.Row():
430
+ rm_name = gr.Textbox(label="Remove a document (file name)", placeholder="e.g. my_policy.pdf")
431
+ rm_btn = gr.Button("🗑️ Remove")
432
+
433
+ # ---------------------------------------------------------------- TAB 3
434
+ with gr.Tab("💬 AI Assistant"):
435
+ with gr.Row():
436
+ mode = gr.Radio(["EvidenceGuard (verified)", "Baseline RAG"], value="EvidenceGuard (verified)",
437
+ label="Answering system")
438
+ chatbot = gr.Chatbot(height=470, label="EvidenceGuard Assistant", render_markdown=True)
439
+ with gr.Row():
440
+ msg = gr.Textbox(placeholder="Ask about attendance, exams, scholarships, library rules... "
441
+ "(follow-up questions are supported)", scale=6, show_label=False)
442
+ send = gr.Button("Ask", variant="primary", scale=1)
443
+ clear = gr.Button("Clear chat", scale=1)
444
+ gr.Examples(EXAMPLES, inputs=msg, label="Try these (include missing-information, misleading and conflicting cases)")
445
+ gr.Markdown("*The full evidence report for the latest answer is in the **Evidence Verification** tab.*")
446
+
447
+ # ---------------------------------------------------------------- TAB 4
448
+ with gr.Tab("🔬 Evidence Verification"):
449
+ gr.Markdown("Shows the retrieved passages, sources, pages, relevance scores, evidence sufficiency, "
450
+ "contradiction status, citation verification and the reason for any abstention.")
451
+ with gr.Row():
452
+ v_q = gr.Textbox(label="Question", placeholder="Type a question, or press 'Show latest chat answer'", scale=4)
453
+ v_cfg = gr.Dropdown(list(CONFIG_NAMES.values()), value=CONFIG_NAMES["full"], label="Configuration", scale=2)
454
+ with gr.Row():
455
+ v_btn = gr.Button("🔍 Verify this question", variant="primary")
456
+ v_last = gr.Button("Show latest chat answer")
457
+ v_md = gr.Markdown(verification_md(None))
458
+ v_df = gr.Dataframe(label="Retrieved passages", interactive=False, wrap=True)
459
+
460
+ # ---------------------------------------------------------------- TAB 5
461
+ with gr.Tab("⚖️ Model Comparison"):
462
+ with gr.Row():
463
+ c_q = gr.Textbox(label="Question", scale=5, value=EXAMPLES[0])
464
+ c_btn = gr.Button("Compare", variant="primary", scale=1)
465
+ gr.Examples(EXAMPLES, inputs=c_q)
466
+ with gr.Row():
467
+ with gr.Column():
468
+ gr.Markdown("### System A - Baseline RAG")
469
+ c_a = gr.Markdown()
470
+ c_pa = gr.Dataframe(label="Baseline evidence", interactive=False, wrap=True)
471
+ with gr.Column():
472
+ gr.Markdown("### System B - EvidenceGuard RAG")
473
+ c_b = gr.Markdown()
474
+ c_pb = gr.Dataframe(label="EvidenceGuard evidence", interactive=False, wrap=True)
475
+ c_perf = gr.Dataframe(label="Performance information", interactive=False)
476
+
477
+ # ---------------------------------------------------------------- TAB 6
478
+ with gr.Tab("📊 Evaluation Dashboard"):
479
+ with gr.Row():
480
+ e_split = gr.Radio(["all", "test", "dev"], value="all", label="Question split")
481
+ e_reload = gr.Button("Reload results")
482
+ e_run = gr.Button("▶️ Re-run evaluation (100 questions × 4 systems)", variant="primary")
483
+ e_status = gr.Markdown()
484
+ e_info = gr.Markdown()
485
+ e_table = gr.Dataframe(label="Metrics (real values from results/metrics.json)", interactive=False)
486
+ with gr.Row():
487
+ ch1 = gr.Image(label="Retrieval comparison")
488
+ ch2 = gr.Image(label="Answer quality & faithfulness")
489
+ with gr.Row():
490
+ ch3 = gr.Image(label="Reliability: unsupported answers, abstention, contradictions")
491
+ ch4 = gr.Image(label="Behaviour accuracy by category")
492
+ with gr.Row():
493
+ ch5 = gr.Image(label="Error analysis")
494
+ ch6 = gr.Image(label="Response time")
495
+ e_cat = gr.Dataframe(label="Category breakdown", interactive=False)
496
+ e_err = gr.Dataframe(label="Error analysis (counts per configuration)", interactive=False)
497
+ e_fail = gr.Dataframe(label="EvidenceGuard failure cases", interactive=False, wrap=True)
498
+
499
+ # ---------------------------------------------------------------- TAB 7
500
+ with gr.Tab("ℹ️ About Project"):
501
+ gr.Markdown(about_md())
502
+ gr.Image(str(ASSETS / "architecture.png"), label="System architecture")
503
+
504
+ # ================================================================ wiring
505
+ up_btn.click(process_uploads, up_files, [up_result, up_kb, up_kb_md, up_status]).then(kb_summary, None, home_kb)
506
+ reset_btn.click(reset_kb, None, [up_result, up_kb, up_kb_md, up_status]).then(kb_summary, None, home_kb)
507
+ rm_btn.click(remove_doc, rm_name, [up_kb, up_kb_md, up_status])
508
+ send.click(chat, [msg, chatbot, mode], [chatbot, msg, last_result])
509
+ msg.submit(chat, [msg, chatbot, mode], [chatbot, msg, last_result])
510
+ clear.click(lambda: ([], None), None, [chatbot, last_result])
511
+ v_btn.click(verify_direct, [v_q, v_cfg], [v_md, v_df, last_result])
512
+ v_last.click(show_last, last_result, [v_md, v_df])
513
+ c_btn.click(compare, c_q, [c_a, c_b, c_pa, c_pb, c_perf])
514
+ eval_outs = [e_table, e_info, e_cat, e_err, e_fail]
515
+ e_reload.click(load_eval, e_split, eval_outs).then(chart_paths, None, [ch1, ch2, ch3, ch4, ch5, ch6])
516
+ e_split.change(load_eval, e_split, eval_outs)
517
+ e_run.click(rerun_eval, e_split, [e_status, *eval_outs, ch1, ch2, ch3, ch4, ch5, ch6])
518
+ demo.load(load_eval, e_split, eval_outs).then(chart_paths, None, [ch1, ch2, ch3, ch4, ch5, ch6])
519
+
520
+
521
+ if __name__ == "__main__":
522
+ demo.queue(default_concurrency_limit=2).launch(
523
+ server_name="0.0.0.0", server_port=int(__import__("os").getenv("PORT", 7860)),
524
+ theme=gr.themes.Soft(primary_hue="blue"), css=CSS, show_error=True, allowed_paths=[str(ASSETS), str(config.CHARTS_DIR)])
assets/architecture.png ADDED

Git LFS Details

  • SHA256: 60157a386c610c1abee3bf190971b37265ee2d6e345a7d70d3239fa206f49cba
  • Pointer size: 131 Bytes
  • Size of remote file: 220 kB
assets/workflow.png ADDED

Git LFS Details

  • SHA256: b853e69092c8c68bd00a1f5236424d29c78a88d7dfd7ecf90da56f207a974398
  • Pointer size: 131 Bytes
  • Size of remote file: 157 kB
config.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Central configuration for EvidenceGuard AI.
3
+
4
+ Every value can be overridden with an environment variable (or a Hugging Face Space
5
+ secret/variable) of the same name. No credentials are stored in code.
6
+
7
+ Backends
8
+ --------
9
+ EG_BACKEND = "auto" | "full" | "lite"
10
+ full : Hugging Face models (Sentence Transformer, cross-encoder reranker, NLI cross-encoder)
11
+ lite : dependency-light, CPU-only fallbacks (TF-IDF+SVD embeddings, lexical reranker,
12
+ rule-based numeric/negation contradiction detector). Used when models cannot be
13
+ downloaded (offline machines) and for fast tests.
14
+ auto : try "full", fall back to "lite" component-by-component if a model cannot load.
15
+
16
+ LLM_BACKEND = "auto" | "hf_api" | "local" | "extractive"
17
+ hf_api : Hugging Face Inference Providers via huggingface_hub (needs HF_TOKEN secret)
18
+ local : small instruction-tuned model run locally with transformers (CPU OK)
19
+ extractive : no LLM; answer is composed from retrieved sentences (fully offline)
20
+ auto : hf_api if HF_TOKEN is set, else local, else extractive
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import os
25
+ from pathlib import Path
26
+
27
+ ROOT = Path(__file__).resolve().parent
28
+ SAMPLE_DATA_DIR = ROOT / "sample_data"
29
+ EVAL_DATA_PATH = ROOT / "evaluation_data" / "questions.json"
30
+ RESULTS_DIR = ROOT / "results"
31
+ CHARTS_DIR = RESULTS_DIR / "charts"
32
+ CACHE_DIR = Path(os.getenv("EG_CACHE_DIR", str(ROOT / ".cache")))
33
+ UPLOAD_DIR = CACHE_DIR / "uploads"
34
+
35
+
36
+ def _env(name: str, default):
37
+ v = os.getenv(name)
38
+ if v is None or v == "":
39
+ return default
40
+ return type(default)(v) if not isinstance(default, bool) else v.lower() in {"1", "true", "yes"}
41
+
42
+
43
+ # ---------------------------------------------------------------- backends
44
+ EG_BACKEND = _env("EG_BACKEND", "auto")
45
+ LLM_BACKEND = _env("LLM_BACKEND", "auto")
46
+
47
+ # ---------------------------------------------------------------- models (all free / open licences)
48
+ EMBEDDING_MODEL = _env("EMBEDDING_MODEL", "sentence-transformers/all-MiniLM-L6-v2")
49
+ RERANKER_MODEL = _env("RERANKER_MODEL", "cross-encoder/ms-marco-MiniLM-L-6-v2")
50
+ NLI_MODEL = _env("NLI_MODEL", "cross-encoder/nli-deberta-v3-xsmall")
51
+ LOCAL_LLM_MODEL = _env("LOCAL_LLM_MODEL", "Qwen/Qwen2.5-0.5B-Instruct")
52
+ HF_API_MODEL = _env("HF_API_MODEL", "Qwen/Qwen2.5-7B-Instruct")
53
+ HF_TOKEN = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACEHUB_API_TOKEN") # Space secret, never hard-coded
54
+
55
+ # ---------------------------------------------------------------- chunking & retrieval
56
+ CHUNK_TARGET_WORDS = _env("CHUNK_TARGET_WORDS", 70)
57
+ CHUNK_OVERLAP_SENTENCES = _env("CHUNK_OVERLAP_SENTENCES", 1)
58
+ TOP_K = _env("TOP_K", 5) # passages given to the generator
59
+ CANDIDATES = _env("CANDIDATES", 20) # candidates pulled by each retriever before fusion/reranking
60
+ RRF_K = _env("RRF_K", 60)
61
+ LSA_DIM = _env("LSA_DIM", 256)
62
+
63
+ # ---------------------------------------------------------------- generation
64
+ MAX_NEW_TOKENS = _env("MAX_NEW_TOKENS", 220)
65
+ TEMPERATURE = _env("TEMPERATURE", 0.0)
66
+
67
+ # ---------------------------------------------------------------- verification thresholds
68
+ # Default values; scripts/run_evaluation.py re-calibrates them on a held-out DEV split
69
+ # and writes results/calibrated_thresholds.json, which is loaded automatically if present.
70
+ THRESHOLDS = {
71
+ "min_relevance": _env("MIN_RELEVANCE", 0.30), # reranker score of best passage
72
+ "min_coverage": _env("MIN_COVERAGE", 0.60), # IDF-weighted query-term coverage
73
+ "partial_coverage": _env("PARTIAL_COVERAGE", 0.45),
74
+ "min_confidence": _env("MIN_CONFIDENCE", 0.40),
75
+ "conflict_topic_sim": _env("CONFLICT_TOPIC_SIM", 0.30), # overlap coefficient (polarity/NLI)
76
+ "conflict_sentence_coverage": _env("CONFLICT_SENT_COV", 0.35), # sentence must cover the question
77
+ "conflict_min_shared": _env("CONFLICT_MIN_SHARED", 2), # shared context words around a value
78
+ "conflict_subject_mismatch": _env("CONFLICT_SUBJECT_MISMATCH", 0.30), # max weight of unshared question words
79
+ "conflict_min_relevance": _env("CONFLICT_MIN_RELEVANCE", 0.25),
80
+ "nli_contradiction": _env("NLI_CONTRADICTION", 0.60),
81
+ "nli_entailment": _env("NLI_ENTAILMENT", 0.50),
82
+ "citation_overlap": _env("CITATION_OVERLAP", 0.50),
83
+ }
84
+
85
+ CALIBRATED_THRESHOLDS_PATH = RESULTS_DIR / "calibrated_thresholds.json"
86
+
87
+
88
+ def load_thresholds(effective_backend: str = "lite") -> dict:
89
+ """Defaults, overridden by calibrated values only if they were calibrated for the same backend
90
+ (reranker scores of the lexical fallback and of the cross-encoder live on different scales)."""
91
+ import json
92
+ th = dict(THRESHOLDS)
93
+ if CALIBRATED_THRESHOLDS_PATH.exists() and not os.getenv("EG_IGNORE_CALIBRATION"):
94
+ try:
95
+ cal = json.loads(CALIBRATED_THRESHOLDS_PATH.read_text())
96
+ if cal.get("backend") == effective_backend:
97
+ th.update(cal.get("thresholds", {}))
98
+ except Exception:
99
+ pass
100
+ return th
101
+
102
+
103
+ for _d in (CACHE_DIR, UPLOAD_DIR, CHARTS_DIR):
104
+ _d.mkdir(parents=True, exist_ok=True)
requirements.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CPU-only PyTorch wheels (much smaller than the default CUDA build) - works on free HF Spaces
2
+ --extra-index-url https://download.pytorch.org/whl/cpu
3
+
4
+ gradio>=6.0
5
+ numpy>=1.26
6
+ pandas>=2.0
7
+ scikit-learn>=1.3
8
+ faiss-cpu>=1.8
9
+ rank-bm25>=0.2.2
10
+ pymupdf>=1.24
11
+ pypdf>=4.0
12
+ reportlab>=4.0
13
+ matplotlib>=3.8
14
+
15
+ # Hugging Face model stack (optional at runtime - the app falls back to offline components if missing)
16
+ torch>=2.2
17
+ transformers>=4.44
18
+ sentence-transformers>=3.0
19
+ huggingface_hub>=0.24
results/calibrated_thresholds.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "lite",
3
+ "thresholds": {
4
+ "min_relevance": 0.15,
5
+ "min_coverage": 0.6,
6
+ "partial_coverage": 0.5,
7
+ "min_confidence": 0.3,
8
+ "conflict_topic_sim": 0.3,
9
+ "conflict_sentence_coverage": 0.35,
10
+ "conflict_min_shared": 2,
11
+ "conflict_subject_mismatch": 0.3,
12
+ "conflict_min_relevance": 0.25,
13
+ "nli_contradiction": 0.6,
14
+ "nli_entailment": 0.5,
15
+ "citation_overlap": 0.5
16
+ },
17
+ "dev_ids": [
18
+ "A06",
19
+ "A07",
20
+ "A11",
21
+ "A12",
22
+ "A13",
23
+ "A15",
24
+ "A20",
25
+ "A23",
26
+ "A27",
27
+ "C08",
28
+ "C11",
29
+ "C12",
30
+ "C13",
31
+ "C16",
32
+ "C20",
33
+ "I03",
34
+ "I08",
35
+ "I10",
36
+ "I12",
37
+ "M03",
38
+ "M10",
39
+ "M12",
40
+ "M13",
41
+ "M14",
42
+ "M15",
43
+ "N01",
44
+ "N09",
45
+ "N11",
46
+ "N15"
47
+ ],
48
+ "dev_behaviour_accuracy": 0.7931,
49
+ "dev_abstention_accuracy": 0.8966,
50
+ "dev_unsupported_rate": 0.069
51
+ }
results/category_breakdown.csv ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ configuration,category,n,answer_correctness,behaviour_accuracy,unsupported_rate,abstention_rate
2
+ Baseline RAG,answerable,30,1.0,1.0,0.0,0.0
3
+ Baseline RAG,conflicting,20,0.1,0.0,0.05,0.0
4
+ Baseline RAG,misleading,15,0.8,0.8,0.1333,0.0
5
+ Baseline RAG,missing,15,0.0,0.0,1.0,0.0
6
+ Baseline RAG,multi_passage,20,0.65,0.65,0.05,0.0
7
+ + Reranking,answerable,30,1.0,1.0,0.0,0.0
8
+ + Reranking,conflicting,20,0.1,0.0,0.05,0.0
9
+ + Reranking,misleading,15,0.8,0.8,0.1333,0.0
10
+ + Reranking,missing,15,0.0,0.0,1.0,0.0
11
+ + Reranking,multi_passage,20,0.6,0.6,0.1,0.0
12
+ + Verification,answerable,30,0.9,0.9,0.0,0.1
13
+ + Verification,conflicting,20,0.65,0.65,0.05,0.2
14
+ + Verification,misleading,15,0.7333,0.7333,0.1333,0.1333
15
+ + Verification,missing,15,0.8,0.8,0.2,0.8
16
+ + Verification,multi_passage,20,0.5,0.5,0.15,0.25
17
+ EvidenceGuard,answerable,30,0.9,0.9,0.0,0.1
18
+ EvidenceGuard,conflicting,20,0.65,0.65,0.05,0.2
19
+ EvidenceGuard,misleading,15,0.7333,0.7333,0.1333,0.1333
20
+ EvidenceGuard,missing,15,0.8,0.8,0.2,0.8
21
+ EvidenceGuard,multi_passage,20,0.5,0.5,0.15,0.25
results/charts/answer_quality_comparison.png ADDED
results/charts/category_breakdown.png ADDED
results/charts/error_analysis.png ADDED
results/charts/reliability_comparison.png ADDED
results/charts/response_time.png ADDED
results/charts/retrieval_comparison.png ADDED
results/error_analysis.csv ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ error_type,Baseline RAG,+ Reranking,+ Verification,EvidenceGuard
2
+ answered unanswerable question (hallucination risk),15,15,3,3
3
+ correct,55,54,73,73
4
+ incomplete answer (some key facts missing),7,7,2,2
5
+ missed conflict,20,20,3,3
6
+ over-abstention (answer was available),0,0,14,14
7
+ wrong/irrelevant answer content,3,4,5,5
results/failure_cases.json ADDED
@@ -0,0 +1,584 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "evidenceguard_failures": [
3
+ {
4
+ "id": "A10",
5
+ "category": "answerable",
6
+ "question": "What are the timings of the afternoon examination session?",
7
+ "expected_behaviour": "answer",
8
+ "error_type": "over-abstention (answer was available)",
9
+ "decision": "abstained",
10
+ "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
11
+ "expected_answer": "2:00 PM to 5:00 PM.",
12
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.53, query coverage 0.58; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: timings.",
13
+ "retrieved": "D06 p.2; D06 p.1; D06 p.1; D06 p.1; D06 p.2",
14
+ "baseline_answer": "Afternoon session: 2:00 PM to 5:00 PM. [3]",
15
+ "baseline_ok": true
16
+ },
17
+ {
18
+ "id": "A17",
19
+ "category": "answerable",
20
+ "question": "What is the amount of the need-based scholarship?",
21
+ "expected_behaviour": "answer",
22
+ "error_type": "over-abstention (answer was available)",
23
+ "decision": "abstained",
24
+ "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
25
+ "expected_answer": "INR 30,000 per year.",
26
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.50, query coverage 0.51; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: amount.",
27
+ "retrieved": "D07 p.1; D08 p.1; D07 p.1; D07 p.2; D08 p.1",
28
+ "baseline_answer": "A need-based scholarship of INR 30,000 per year is available to students whose annual family income does not exceed INR 6,00,000. [1]",
29
+ "baseline_ok": true
30
+ },
31
+ {
32
+ "id": "A24",
33
+ "category": "answerable",
34
+ "question": "How far in advance must an application for academic leave be submitted?",
35
+ "expected_behaviour": "answer",
36
+ "error_type": "over-abstention (answer was available)",
37
+ "decision": "abstained",
38
+ "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
39
+ "expected_answer": "At least 30 days before the start of the semester (except medical emergencies).",
40
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.28, query coverage 0.50; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: far, advance.",
41
+ "retrieved": "D10 p.1; D10 p.1; D07 p.1; D10 p.2; D10 p.1",
42
+ "baseline_answer": "Applications must be submitted to the Dean of Academics at least 30 days before the start of the semester, except in medical emergencies. [1] Students may avail maternity leave of up to 6 months, which is counted within the academic leave limit. [1]",
43
+ "baseline_ok": true
44
+ },
45
+ {
46
+ "id": "M01",
47
+ "category": "multi_passage",
48
+ "question": "What minimum internal assessment marks are needed for exam eligibility, and how many marks is each internal test worth?",
49
+ "expected_behaviour": "answer",
50
+ "error_type": "over-abstention (answer was available)",
51
+ "decision": "abstained",
52
+ "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
53
+ "expected_answer": "At least 16 out of 40 IA marks (40%); each internal test is worth 15 marks.",
54
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.35, query coverage 0.49; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: minimum, exam, worth.",
55
+ "retrieved": "D04 p.1; D03 p.1; D04 p.1; D04 p.2; D04 p.1",
56
+ "baseline_answer": "Internal assessment consists of Internal Test 1 (15 marks), Internal Test 2 (15 marks), Assignment (5 marks), and Class participation and quizzes (5 marks). [1]",
57
+ "baseline_ok": false
58
+ },
59
+ {
60
+ "id": "M02",
61
+ "category": "multi_passage",
62
+ "question": "When is Internal Test 1 held this semester, and what must a student do to take a make-up test if they miss it through illness?",
63
+ "expected_behaviour": "answer",
64
+ "error_type": "over-abstention (answer was available)",
65
+ "decision": "abstained",
66
+ "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
67
+ "expected_answer": "1-5 September 2025; submit a medical certificate within 3 working days to take one make-up test.",
68
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.33, query coverage 0.56; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: held, through, illness.",
69
+ "retrieved": "D04 p.1; D04 p.1; D04 p.1; D14 p.1; D14 p.1",
70
+ "baseline_answer": "A student who misses an internal test on medical grounds may take one make-up test per semester, provided a medical certificate is submitted within 3 working days of the missed test. [1]",
71
+ "baseline_ok": false
72
+ },
73
+ {
74
+ "id": "M03",
75
+ "category": "multi_passage",
76
+ "question": "What happens to a student whose attendance is still short after condonation, and to whom can an eligibility decision be appealed?",
77
+ "expected_behaviour": "answer",
78
+ "error_type": "over-abstention (answer was available)",
79
+ "decision": "abstained",
80
+ "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
81
+ "expected_answer": "They are marked NE (Not Eligible) and must re-register; appeals go to the Controller of Examinations within 3 working days.",
82
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.19, query coverage 0.42; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: happens, still, short.",
83
+ "retrieved": "D03 p.2; D02 p.1; D01 p.1; D03 p.1; D01 p.1",
84
+ "baseline_answer": "A student may appeal against an eligibility decision to the Controller of Examinations within 3 working days of the publication of the eligibility list. [1]",
85
+ "baseline_ok": false
86
+ },
87
+ {
88
+ "id": "M08",
89
+ "category": "multi_passage",
90
+ "question": "How many internal assessment marks are given for assignments, and in what file format must assignments be submitted?",
91
+ "expected_behaviour": "answer",
92
+ "error_type": "wrong/irrelevant answer content",
93
+ "decision": "conflict",
94
+ "answer": "\u26a0\ufe0f **Conflicting evidence found.** The documents disagree:\n- *Internal Assessment Guidelines 2024* (issued 2024-05-20): Assignments submitted after the deadline will not be accepted for internal assessment. [1]\n- *Assignment Submission Policy 2024* (issued 2024-06-10): Late submissions are accepted for up to 3 calendar days after the deadline with a penalty of 10% of the maximum marks per day. [2]\nThe more recent document is *Assignment Submission Policy 2024*. Please confirm with the issuing office before relying on either version.\n**Most relevant evidence:** IA marks are published on AVU-Learn within 10 working days of each test. [1]",
95
+ "expected_answer": "5 marks; as a single PDF file (max 10 MB).",
96
+ "explanation": "Answered with a conflict warning: 'Internal Assessment Guidelines 2024' and 'Assignment Submission Policy 2024' disagree (one passage permits what the other rules out).",
97
+ "retrieved": "D04 p.2; D05 p.1; D05 p.1; D04 p.1; D04 p.1; D14 p.1",
98
+ "baseline_answer": "Assignments submitted after the deadline will not be accepted for internal assessment. [1] IA marks are published on AVU-Learn within 10 working days of each test. [1] Assignments must be submitted as a single PDF file of no more than 10 MB. [2]",
99
+ "baseline_ok": false
100
+ },
101
+ {
102
+ "id": "M11",
103
+ "category": "multi_passage",
104
+ "question": "What documents must be submitted for the need-based scholarship, and how recent must the income certificate be?",
105
+ "expected_behaviour": "answer",
106
+ "error_type": "wrong/irrelevant answer content",
107
+ "decision": "conflict",
108
+ "answer": "\u26a0\ufe0f **Conflicting evidence found.** The documents disagree:\n- *Scholarship Policy 2025-26* (issued 2025-05-01): A need-based scholarship of INR 30,000 per year is available to students whose annual family income does not exceed INR 6,00,000. [1]\n- *Notice: Revision of Scholarship Deadline and Income Ceiling* (issued 2025-08-25): The family income ceiling for the need-based scholarship is revised to INR 8,00,000. [2]\nThe more recent document is *Notice: Revision of Scholarship Deadline and Income Ceiling*, which explicitly revises the earlier rule. Please confirm with the issuing office before relying on either version.\n**Most relevant evidence:** A student who misses an internal test on medical grounds may take one make-up test per semester, provided a medical certificate is submitted within 3 working days of the missed test. [5]",
109
+ "expected_answer": "An income certificate from a competent authority issued within the last 6 months, and the previous year's marks card.",
110
+ "explanation": "Answered with a conflict warning: 'Scholarship Policy 2025-26' and 'Notice: Revision of Scholarship Deadline and Income Ceiling' disagree (inr: 600000 vs 800000 (context: family, income)).",
111
+ "retrieved": "D07 p.1; D08 p.1; D07 p.1; D08 p.1; D04 p.1",
112
+ "baseline_answer": "A need-based scholarship of INR 30,000 per year is available to students whose annual family income does not exceed INR 6,00,000. [1] Applications must be submitted on AVU-Learn by 31 August 2025. [1] Applicants must submit an income certificate issued by a competent authority within the last 6 months and the marks card of the previous year. [1]",
113
+ "baseline_ok": true
114
+ },
115
+ {
116
+ "id": "M12",
117
+ "category": "multi_passage",
118
+ "question": "If a student qualifies for both the merit and need-based scholarships, what do they receive, and what is needed to renew it?",
119
+ "expected_behaviour": "answer",
120
+ "error_type": "incomplete answer (some key facts missing)",
121
+ "decision": "answered",
122
+ "answer": "Scholarships are renewed annually subject to a CGPA of at least 8.0 and no disciplinary action. [2] Students with a CGPA of 9.0 or above in the previous academic year receive a 50% tuition fee waiver. [1] A need-based scholarship of INR 30,000 per year is available to students whose annual family income does not exceed INR 6,00,000. [5]",
123
+ "expected_answer": "Only the higher-value scholarship; renewal needs a CGPA of at least 8.0 and no disciplinary action.",
124
+ "explanation": "Answered: relevance 0.34, coverage 0.68, 3/3 sentences verified against their citations.",
125
+ "retrieved": "D07 p.1; D07 p.2; D07 p.2; D05 p.1; D07 p.1",
126
+ "baseline_answer": "Scholarships are renewed annually subject to a CGPA of at least 8.0 and no disciplinary action. [2] Students with a CGPA of 9.0 or above in the previous academic year receive a 50% tuition fee waiver. [1] A need-based scholarship of INR 30,000 per year is available to students whose annual family income does not exceed INR 6,00,000. [3]",
127
+ "baseline_ok": false
128
+ },
129
+ {
130
+ "id": "M16",
131
+ "category": "multi_passage",
132
+ "question": "Which MSc Data Science Semester 3 examination is held in the afternoon session, and what are the afternoon session timings?",
133
+ "expected_behaviour": "answer",
134
+ "error_type": "incomplete answer (some key facts missing)",
135
+ "decision": "answered",
136
+ "answer": "10 December 2025 (Wednesday): MDS305 Security for Data Science - Afternoon session. [2] MSc Data Science - Semester 3. [1] Supplementary examinations are held in June and July; the maximum grade awarded in a supplementary examination is grade A. [5]",
137
+ "expected_answer": "MDS305 Security for Data Science on 10 December 2025; 2:00 PM to 5:00 PM.",
138
+ "explanation": "Answered: relevance 0.50, coverage 0.62, 3/3 sentences verified against their citations.",
139
+ "retrieved": "D06 p.1; D06 p.1; D06 p.2; D06 p.1; D13 p.2",
140
+ "baseline_answer": "10 December 2025 (Wednesday): MDS305 Security for Data Science - Afternoon session. [2] MSc Data Science - Semester 3. [1]",
141
+ "baseline_ok": false
142
+ },
143
+ {
144
+ "id": "M18",
145
+ "category": "multi_passage",
146
+ "question": "How many backlog courses prevent promotion to the next year, and when can backlogs be cleared through supplementary examinations?",
147
+ "expected_behaviour": "answer",
148
+ "error_type": "over-abstention (answer was available)",
149
+ "decision": "abstained",
150
+ "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
151
+ "expected_answer": "More than 4 backlog courses; supplementary exams are held in June and July.",
152
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.35, query coverage 0.52; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: prevent, promotion, through.",
153
+ "retrieved": "D13 p.2; D03 p.2; D03 p.2; D11 p.2; D03 p.1",
154
+ "baseline_answer": "A student with more than 4 backlog courses at the end of an academic year will not be promoted to the next year. [1] Supplementary examinations are held in June and July; the maximum grade awarded in a supplementary examination is grade A. [1] Library dues do not affect examination eligibility but must be cleared before results are released. [2]",
155
+ "baseline_ok": true
156
+ },
157
+ {
158
+ "id": "M19",
159
+ "category": "multi_passage",
160
+ "question": "How is participation in university-approved events treated for attendance, and who must approve it?",
161
+ "expected_behaviour": "answer",
162
+ "error_type": "over-abstention (answer was available)",
163
+ "decision": "abstained",
164
+ "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
165
+ "expected_answer": "Counted as present for up to 10 contact hours per semester with prior approval of the Head of Department.",
166
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.49, query coverage 0.56; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: treated, approve.",
167
+ "retrieved": "D01 p.2; D04 p.1; D04 p.1; D01 p.1; D02 p.1",
168
+ "baseline_answer": "Participation in university-approved events such as sports, cultural festivals and NCC camps is counted as present for up to 10 contact hours per semester, with prior approval of the Head of Department. [1]",
169
+ "baseline_ok": true
170
+ },
171
+ {
172
+ "id": "M20",
173
+ "category": "multi_passage",
174
+ "question": "A student returning from academic leave must re-register within which window, and what are the regular odd semester registration dates?",
175
+ "expected_behaviour": "answer",
176
+ "error_type": "wrong/irrelevant answer content",
177
+ "decision": "answered",
178
+ "answer": "Students returning from leave must re-register within the regular registration window. [1] Key Dates - Odd Semester 2025-26. [4]",
179
+ "expected_answer": "Within the regular registration window: 1 July 2025 to 15 July 2025.",
180
+ "explanation": "Answered: relevance 0.64, coverage 0.84, 2/2 sentences verified against their citations.",
181
+ "retrieved": "D10 p.2; D10 p.2; D09 p.1; D14 p.1; D10 p.1",
182
+ "baseline_answer": "Students returning from leave must re-register within the regular registration window. [1] Key Dates - Odd Semester 2025-26. [5]",
183
+ "baseline_ok": false
184
+ },
185
+ {
186
+ "id": "N09",
187
+ "category": "missing",
188
+ "question": "What is the fee for a duplicate hall ticket?",
189
+ "expected_behaviour": "abstain",
190
+ "error_type": "answered unanswerable question (hallucination risk)",
191
+ "decision": "answered",
192
+ "answer": "Hall tickets are issued through the AVU-Learn portal 5 days before the first examination. [1] (c) The student must have no outstanding tuition fee dues. [1]",
193
+ "expected_answer": "The documents do not contain this information; the system should abstain.",
194
+ "explanation": "Answered: relevance 0.57, coverage 0.65, 2/2 sentences verified against their citations.",
195
+ "retrieved": "D03 p.1; D06 p.2; D07 p.1; D01 p.1; D03 p.1; D05 p.1",
196
+ "baseline_answer": "Hall tickets are issued through the AVU-Learn portal 5 days before the first examination. [1] (c) The student must have no outstanding tuition fee dues. [1]",
197
+ "baseline_ok": false
198
+ },
199
+ {
200
+ "id": "N13",
201
+ "category": "missing",
202
+ "question": "What is the late fine for paying tuition fees after the due date?",
203
+ "expected_behaviour": "abstain",
204
+ "error_type": "answered unanswerable question (hallucination risk)",
205
+ "decision": "answered",
206
+ "answer": "Late payment of hostel dues attracts a fine of INR 500. [1] Students on academic leave are not charged tuition fees for the leave semester but must pay a registration retention fee of INR 5,000 per semester. [4] Instructors must announce assignment topics at least two weeks before the due date. [2]",
207
+ "expected_answer": "The documents do not contain this information; the system should abstain.",
208
+ "explanation": "Answered: relevance 0.30, coverage 0.62, 3/3 sentences verified against their citations.",
209
+ "retrieved": "D16 p.1; D04 p.2; D05 p.1; D10 p.2; D09 p.1; D05 p.1",
210
+ "baseline_answer": "Students on academic leave are not charged tuition fees for the leave semester but must pay a registration retention fee of INR 5,000 per semester. [1] Late payment of hostel dues attracts a fine of INR 500. [2]",
211
+ "baseline_ok": false
212
+ },
213
+ {
214
+ "id": "N15",
215
+ "category": "missing",
216
+ "question": "What is the timetable for the even semester examinations in May 2026?",
217
+ "expected_behaviour": "abstain",
218
+ "error_type": "answered unanswerable question (hallucination risk)",
219
+ "decision": "answered",
220
+ "answer": "Even semester classes begin on 5 January 2026. [2] Only non-programmable scientific calculators are permitted in the examination hall. [1]",
221
+ "expected_answer": "The documents do not contain this information; the system should abstain.",
222
+ "explanation": "Answered: relevance 0.52, coverage 0.83, 2/2 sentences verified against their citations.",
223
+ "retrieved": "D06 p.2; D14 p.2; D06 p.1; D06 p.1; D06 p.1; D14 p.1",
224
+ "baseline_answer": "Even semester classes begin on 5 January 2026. [3] Only non-programmable scientific calculators are permitted in the examination hall. [1]",
225
+ "baseline_ok": false
226
+ },
227
+ {
228
+ "id": "I05",
229
+ "category": "misleading",
230
+ "question": "Given that academic leave can be taken for up to four semesters, how early must a student apply?",
231
+ "expected_behaviour": "correct_premise",
232
+ "error_type": "over-abstention (answer was available)",
233
+ "decision": "abstained",
234
+ "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
235
+ "expected_answer": "Academic leave is limited to two semesters; apply at least 30 days before the semester.",
236
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.35, query coverage 0.35; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: taken, four, early.",
237
+ "retrieved": "D10 p.1; D10 p.2; D10 p.1; D10 p.1; D10 p.2",
238
+ "baseline_answer": "A student may apply for academic leave (leave of absence) for a maximum of two semesters during the entire programme. [1]",
239
+ "baseline_ok": false
240
+ },
241
+ {
242
+ "id": "I06",
243
+ "category": "misleading",
244
+ "question": "As the MDS301 Deep Learning exam is in the afternoon session, what time does it start?",
245
+ "expected_behaviour": "correct_premise",
246
+ "error_type": "wrong/irrelevant answer content",
247
+ "decision": "answered",
248
+ "answer": "01 December 2025 (Monday): MDS301 Deep Learning - Morning session. [1]",
249
+ "expected_answer": "It is in the morning session (01 December 2025), which starts at 10:00 AM.",
250
+ "explanation": "Answered: relevance 0.53, coverage 0.73, 1/1 sentences verified against their citations.",
251
+ "retrieved": "D06 p.1; D06 p.1; D06 p.2; D06 p.1; D07 p.2",
252
+ "baseline_answer": "01 December 2025 (Monday): MDS301 Deep Learning - Morning session. [1]",
253
+ "baseline_ok": false
254
+ },
255
+ {
256
+ "id": "I13",
257
+ "category": "misleading",
258
+ "question": "What is the minimum CGPA for First Class (without distinction)?",
259
+ "expected_behaviour": "answer",
260
+ "error_type": "wrong/irrelevant answer content",
261
+ "decision": "answered",
262
+ "answer": "First Class with Distinction is awarded for a CGPA of 8.0 or above. [1] Scholarship holders must maintain a minimum of 75% attendance in every course. [3]",
263
+ "expected_answer": "6.5 (First Class is CGPA 6.5 to 7.99).",
264
+ "explanation": "Answered: relevance 0.52, coverage 0.68, 2/2 sentences verified against their citations.",
265
+ "retrieved": "D13 p.2; D13 p.2; D07 p.2; D03 p.1; D01 p.1",
266
+ "baseline_answer": "First Class with Distinction is awarded for a CGPA of 8.0 or above. [1] Scholarship holders must maintain a minimum of 75% attendance in every course. [3]",
267
+ "baseline_ok": false
268
+ },
269
+ {
270
+ "id": "I15",
271
+ "category": "misleading",
272
+ "question": "Is a calculator with programmable memory allowed in the examination hall?",
273
+ "expected_behaviour": "answer",
274
+ "error_type": "over-abstention (answer was available)",
275
+ "decision": "abstained",
276
+ "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
277
+ "expected_answer": "No - only non-programmable scientific calculators are permitted.",
278
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.22, query coverage 0.46; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: programmable, memory.",
279
+ "retrieved": "D06 p.2; D03 p.1; D03 p.1; D06 p.1; D03 p.1",
280
+ "baseline_answer": "Only non-programmable scientific calculators are permitted in the examination hall. [2]",
281
+ "baseline_ok": true
282
+ },
283
+ {
284
+ "id": "C02",
285
+ "category": "conflicting",
286
+ "question": "Up to what percentage can an attendance shortage be condoned on medical grounds?",
287
+ "expected_behaviour": "flag_conflict",
288
+ "error_type": "over-abstention (answer was available)",
289
+ "decision": "abstained",
290
+ "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
291
+ "expected_answer": "Conflict: 10% under the 2023 regulations; limited to 5% by the 2025 circular.",
292
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.43, query coverage 0.50; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: percentage, condoned.",
293
+ "retrieved": "D01 p.1; D01 p.1; D02 p.1; D02 p.1; D01 p.1",
294
+ "baseline_answer": "The Dean of Academics may condone a shortage of attendance of up to 10% (that is, attendance between 65% and 75%) on documented medical grounds. [1]",
295
+ "baseline_ok": false
296
+ },
297
+ {
298
+ "id": "C04",
299
+ "category": "conflicting",
300
+ "question": "According to the examination eligibility rules, what attendance is needed in a course to sit its end-semester exam?",
301
+ "expected_behaviour": "flag_conflict",
302
+ "error_type": "missed conflict",
303
+ "decision": "answered",
304
+ "answer": "These rules determine whether a student may appear for the end-semester examination of a course. [1] A student may appeal against an eligibility decision to the Controller of Examinations within 3 working days of the publication of the eligibility list. [4]",
305
+ "expected_answer": "Conflict: the eligibility rules (2024) state 75%, but the 2025 circular raises the requirement to 80%.",
306
+ "explanation": "Answered: relevance 0.49, coverage 0.62, 2/2 sentences verified against their citations.",
307
+ "retrieved": "D03 p.1; D03 p.1; D06 p.1; D03 p.2; D01 p.1",
308
+ "baseline_answer": "These rules determine whether a student may appear for the end-semester examination of a course. [1] Students declared not eligible must re-register for the course when it is next offered and satisfy all eligibility conditions afresh. [2]",
309
+ "baseline_ok": false
310
+ },
311
+ {
312
+ "id": "C16",
313
+ "category": "conflicting",
314
+ "question": "If my attendance in a course is 78%, am I eligible for the end-semester examination?",
315
+ "expected_behaviour": "flag_conflict",
316
+ "error_type": "missed conflict",
317
+ "decision": "partial",
318
+ "answer": "A student must secure a minimum of 75% attendance in each course to be eligible to appear for the end-semester examination of that course. [2]",
319
+ "expected_answer": "Conflict: eligible under the 2023 rule (75%), but below the 80% minimum under the 2025 circular (condonable between 75% and 80%).",
320
+ "explanation": "Partially answered: query coverage 0.56; not covered: 78%.",
321
+ "retrieved": "D03 p.1; D01 p.1; D01 p.1; D03 p.1; D01 p.2; D03 p.2",
322
+ "baseline_answer": "A student must secure a minimum of 75% attendance in each course to be eligible to appear for the end-semester examination of that course. [1]",
323
+ "baseline_ok": false
324
+ },
325
+ {
326
+ "id": "C17",
327
+ "category": "conflicting",
328
+ "question": "If a PG student scores 45% in aggregate in a course, do they pass?",
329
+ "expected_behaviour": "flag_conflict",
330
+ "error_type": "over-abstention (answer was available)",
331
+ "decision": "abstained",
332
+ "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
333
+ "expected_answer": "Conflict: pass under the Grading Policy (40%), fail under the PG Handbook (50%).",
334
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.41, query coverage 0.46; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: scores, 45%.",
335
+ "retrieved": "D15 p.1; D15 p.1; D13 p.1; D13 p.1; D09 p.1",
336
+ "baseline_answer": "PG students must obtain at least 50% marks in aggregate to pass a course. [1]",
337
+ "baseline_ok": false
338
+ },
339
+ {
340
+ "id": "C18",
341
+ "category": "conflicting",
342
+ "question": "What is the lowest attendance percentage that can be condoned on medical grounds?",
343
+ "expected_behaviour": "flag_conflict",
344
+ "error_type": "over-abstention (answer was available)",
345
+ "decision": "abstained",
346
+ "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
347
+ "expected_answer": "Conflict: 65% under the 2023 regulations vs 75% under the 2025 circular.",
348
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.27, query coverage 0.30; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: lowest, percentage, condoned.",
349
+ "retrieved": "D01 p.1; D02 p.1; D02 p.1; D01 p.1; D01 p.1",
350
+ "baseline_answer": "The Dean of Academics may condone a shortage of attendance of up to 10% (that is, attendance between 65% and 75%) on documented medical grounds. [1] Attendance percentage is the number of contact hours attended divided by the number of contact hours conducted in a course, multiplied by 100. [2]",
351
+ "baseline_ok": false
352
+ },
353
+ {
354
+ "id": "C19",
355
+ "category": "conflicting",
356
+ "question": "Which attendance rule is the latest, and what minimum attendance does it require?",
357
+ "expected_behaviour": "flag_conflict",
358
+ "error_type": "over-abstention (answer was available)",
359
+ "decision": "abstained",
360
+ "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
361
+ "expected_answer": "Conflict: the 2025 circular (latest) requires 80%, superseding the 75% of the 2023 regulations.",
362
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.38, query coverage 0.46; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: latest.",
363
+ "retrieved": "D01 p.1; D02 p.1; D01 p.1; D07 p.2; D09 p.1",
364
+ "baseline_answer": "A student must secure a minimum of 75% attendance in each course to be eligible to appear for the end-semester examination of that course. [1]",
365
+ "baseline_ok": false
366
+ },
367
+ {
368
+ "id": "C20",
369
+ "category": "conflicting",
370
+ "question": "According to the academic calendar, what is the scholarship application deadline, and has it changed?",
371
+ "expected_behaviour": "flag_conflict",
372
+ "error_type": "missed conflict",
373
+ "decision": "answered",
374
+ "answer": "Last date for scholarship applications: 31 August 2025. [1] Late submissions are accepted for up to 3 calendar days after the deadline with a penalty of 10% of the maximum marks per day. [3]",
375
+ "expected_answer": "Conflict: the calendar says 31 August 2025, but the notice extends it to 15 September 2025.",
376
+ "explanation": "Answered: relevance 0.31, coverage 0.64, 2/2 sentences verified against their citations.",
377
+ "retrieved": "D14 p.1; D07 p.1; D05 p.1; D08 p.1; D08 p.1",
378
+ "baseline_answer": "Last date for scholarship applications: 31 August 2025. [1]",
379
+ "baseline_ok": false
380
+ }
381
+ ],
382
+ "evidenceguard_fixes_over_baseline": [
383
+ {
384
+ "id": "N01",
385
+ "category": "missing",
386
+ "question": "What is the fee for revaluation of answer scripts?",
387
+ "baseline_answer": "Answer scripts of internal tests are retained by the department for one year. [1] Students with a CGPA of 9.0 or above in the previous academic year receive a 50% tuition fee waiver. [2]",
388
+ "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
389
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.45, query coverage 0.60; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: revaluation."
390
+ },
391
+ {
392
+ "id": "N02",
393
+ "category": "missing",
394
+ "question": "Who is the current Vice-Chancellor of Aranya Valley University?",
395
+ "baseline_answer": "Students returning from leave must re-register within the regular registration window. [1]",
396
+ "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
397
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.31, query coverage 0.41; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: vice-chancellor."
398
+ },
399
+ {
400
+ "id": "N03",
401
+ "category": "missing",
402
+ "question": "What is the annual hostel fee for PhD students?",
403
+ "baseline_answer": "Late payment of hostel dues attracts a fine of INR 500. [1] A need-based scholarship of INR 30,000 per year is available to students whose annual family income does not exceed INR 6,00,000. [3] The mess fee is INR 4,500 per month, payable by the 10th of each month. [1]",
404
+ "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
405
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.30, query coverage 0.51; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: phd."
406
+ },
407
+ {
408
+ "id": "N04",
409
+ "category": "missing",
410
+ "question": "Does the university offer a sports quota scholarship?",
411
+ "baseline_answer": "Participation in university-approved events such as sports, cultural festivals and NCC camps is counted as present for up to 10 contact hours per semester, with prior approval of the Head of Department. [5] All other conditions of the Scholarship Policy 2025-26 remain unchanged. [1]",
412
+ "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
413
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.19, query coverage 0.36; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: offer, quota."
414
+ },
415
+ {
416
+ "id": "N05",
417
+ "category": "missing",
418
+ "question": "What is the dress code during end-semester examinations?",
419
+ "baseline_answer": "End-semester examinations: from 3 December 2025. [1]",
420
+ "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
421
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.26, query coverage 0.22; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: dress, code."
422
+ },
423
+ {
424
+ "id": "N06",
425
+ "category": "missing",
426
+ "question": "Can students take the end-semester examinations online from home?",
427
+ "baseline_answer": "The odd semester end-semester examinations commence on 1 December 2025 and conclude on 12 December 2025. [1]",
428
+ "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
429
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.20, query coverage 0.17; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: take, online, home."
430
+ },
431
+ {
432
+ "id": "N07",
433
+ "category": "missing",
434
+ "question": "What minimum CGPA is required to sit for campus placements?",
435
+ "baseline_answer": "Campus Wi-Fi is available to residents with a daily limit of 5 GB. [1] First Class is awarded for a CGPA from 6.5 to 7.99. [2] Scholarship holders must maintain a minimum of 75% attendance in every course. [3]",
436
+ "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
437
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.22, query coverage 0.36; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: sit, placements."
438
+ },
439
+ {
440
+ "id": "N08",
441
+ "category": "missing",
442
+ "question": "How many total credits are required to graduate from the MSc Data Science programme?",
443
+ "baseline_answer": "MSc Data Science - Semester 3. [1] The PG dissertation carries 12 credits and is evaluated by an internal guide and an external examiner. [3]",
444
+ "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
445
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.35, query coverage 0.51; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: total, graduate."
446
+ },
447
+ {
448
+ "id": "N10",
449
+ "category": "missing",
450
+ "question": "On what date will the 2026 convocation ceremony be held?",
451
+ "baseline_answer": "Supplementary examinations are held in June and July; the maximum grade awarded in a supplementary examination is grade A. [1] Instructors must announce assignment topics at least two weeks before the due date. [4]",
452
+ "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
453
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.15, query coverage 0.28; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: date, convocation, ceremony."
454
+ },
455
+ {
456
+ "id": "N11",
457
+ "category": "missing",
458
+ "question": "What is the university policy on using generative AI tools such as ChatGPT in assignments?",
459
+ "baseline_answer": "03 December 2025 (Wednesday): MDS302 Generative AI and LLMs - Morning session. [1] Subscribed e-journals can be accessed off campus through the library remote access service using university credentials. [2]",
460
+ "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
461
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.28, query coverage 0.46; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: tools, chatgpt."
462
+ },
463
+ {
464
+ "id": "N12",
465
+ "category": "missing",
466
+ "question": "What is the parking fee for students' two-wheelers on campus?",
467
+ "baseline_answer": "The mess fee is INR 4,500 per month, payable by the 10th of each month. [2] Campus Wi-Fi is available to residents with a daily limit of 5 GB. [1]",
468
+ "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
469
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.25, query coverage 0.33; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: parking, two-wheelers."
470
+ },
471
+ {
472
+ "id": "N14",
473
+ "category": "missing",
474
+ "question": "Does the university offer a tuition fee concession for siblings?",
475
+ "baseline_answer": "Students on academic leave are not charged tuition fees for the leave semester but must pay a registration retention fee of INR 5,000 per semester. [4]",
476
+ "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.",
477
+ "explanation": "Abstained: evidence is insufficient (best passage relevance 0.24, query coverage 0.27; thresholds 0.15 / 0.60). Question terms not found in the retrieved passages: offer, concession, siblings."
478
+ },
479
+ {
480
+ "id": "C01",
481
+ "category": "conflicting",
482
+ "question": "What is the minimum attendance required to appear for end-semester examinations?",
483
+ "baseline_answer": "A student must secure a minimum of 75% attendance in each course to be eligible to appear for the end-semester examination of that course. [1]",
484
+ "evidenceguard_answer": "\u26a0\ufe0f **Conflicting evidence found.** The documents disagree:\n- *Attendance Regulations 2023* (issued 2023-06-15): A student must secure a minimum of 75% attendance in each course to be eligible to appear for the end-semester examination of that course. [1]\n- *Circular: Amendment to Attendance Regulations* (issued 2025-06-02): With effect from the academic year 2025-26, the minimum attendance requirement for each course is revised to 80%. [5]\nThe more recent document is *Circular: Amendment to Attendance Regulations*, which explicitly revises the earlier rule. Please confirm with the issuing office before relying on either version.",
485
+ "explanation": "Answered with a conflict warning: 'Attendance Regulations 2023' and 'Circular: Amendment to Attendance Regulations' disagree (%: 75 vs 80 (context: attendance, minimum))."
486
+ },
487
+ {
488
+ "id": "C03",
489
+ "category": "conflicting",
490
+ "question": "What is the condonation fee per course for attendance shortage?",
491
+ "baseline_answer": "A condonation fee of INR 500 per course is payable before the condonation order is issued. [1] The Dean of Academics may condone a shortage of attendance of up to 10% (that is, attendance between 65% and 75%) on documented medical grounds. [1]",
492
+ "evidenceguard_answer": "\u26a0\ufe0f **Conflicting evidence found.** The documents disagree:\n- *Attendance Regulations 2023* (issued 2023-06-15): A condonation fee of INR 500 per course is payable before the condonation order is issued. [1]\n- *Circular: Amendment to Attendance Regulations* (issued 2025-06-02): The condonation fee is revised to INR 1,000 per course. [4]\nThe more recent document is *Circular: Amendment to Attendance Regulations*, which explicitly revises the earlier rule. Please confirm with the issuing office before relying on either version.\n**Most relevant evidence:** The Dean of Academics may condone a shortage of attendance of up to 10% (that is, attendance between 65% and 75%) on documented medical grounds. [1]",
493
+ "explanation": "Answered with a conflict warning: 'Attendance Regulations 2023' and 'Circular: Amendment to Attendance Regulations' disagree (inr: 500 vs 1000 (context: condonation, fee))."
494
+ },
495
+ {
496
+ "id": "C05",
497
+ "category": "conflicting",
498
+ "question": "What is the last date to apply for a scholarship for 2025-26?",
499
+ "baseline_answer": "The last date for scholarship applications for 2025-26 is extended to 15 September 2025. [1]",
500
+ "evidenceguard_answer": "\u26a0\ufe0f **Conflicting evidence found.** The documents disagree:\n- *Notice: Revision of Scholarship Deadline and Income Ceiling* (issued 2025-08-25): The last date for scholarship applications for 2025-26 is extended to 15 September 2025. [1]\n- *Academic Calendar 2025-26 (Odd Semester)* (issued 2025-06-15): Last date for scholarship applications: 31 August 2025. [2]\nThe more recent document is *Notice: Revision of Scholarship Deadline and Income Ceiling*, which explicitly revises the earlier rule. Please confirm with the issuing office before relying on either version.",
501
+ "explanation": "Answered with a conflict warning: 'Notice: Revision of Scholarship Deadline and Income Ceiling' and 'Academic Calendar 2025-26 (Odd Semester)' disagree (date: 15 september 2025 vs 31 august 2025 (context: application, date, last, scholarship))."
502
+ },
503
+ {
504
+ "id": "C06",
505
+ "category": "conflicting",
506
+ "question": "What is the family income limit for the need-based scholarship?",
507
+ "baseline_answer": "A need-based scholarship of INR 30,000 per year is available to students whose annual family income does not exceed INR 6,00,000. [1]",
508
+ "evidenceguard_answer": "\u26a0\ufe0f **Conflicting evidence found.** The documents disagree:\n- *Notice: Revision of Scholarship Deadline and Income Ceiling* (issued 2025-08-25): The family income ceiling for the need-based scholarship is revised to INR 8,00,000. [1]\n- *Scholarship Policy 2025-26* (issued 2025-05-01): A need-based scholarship of INR 30,000 per year is available to students whose annual family income does not exceed INR 6,00,000. [2]\nThe more recent document is *Notice: Revision of Scholarship Deadline and Income Ceiling*, which explicitly revises the earlier rule. Please confirm with the issuing office before relying on either version.\n**Most relevant evidence:** Students may avail maternity leave of up to 6 months, which is counted within the academic leave limit. [5]",
509
+ "explanation": "Answered with a conflict warning: 'Notice: Revision of Scholarship Deadline and Income Ceiling' and 'Scholarship Policy 2025-26' disagree (inr: 800000 vs 600000 (context: family, income))."
510
+ },
511
+ {
512
+ "id": "C07",
513
+ "category": "conflicting",
514
+ "question": "Are late assignment submissions accepted?",
515
+ "baseline_answer": "Late submissions are accepted for up to 3 calendar days after the deadline with a penalty of 10% of the maximum marks per day. [1] Assignments must be submitted as a single PDF file of no more than 10 MB. [1]",
516
+ "evidenceguard_answer": "\u26a0\ufe0f **Conflicting evidence found.** The documents disagree:\n- *Assignment Submission Policy 2024* (issued 2024-06-10): Late submissions are accepted for up to 3 calendar days after the deadline with a penalty of 10% of the maximum marks per day. [1]\n- *Internal Assessment Guidelines 2024* (issued 2024-05-20): Assignments submitted after the deadline will not be accepted for internal assessment. [3]\nThe more recent document is *Assignment Submission Policy 2024*. Please confirm with the issuing office before relying on either version.\n**Most relevant evidence:** Assignments must be submitted as a single PDF file of no more than 10 MB. [1]",
517
+ "explanation": "Answered with a conflict warning: 'Assignment Submission Policy 2024' and 'Internal Assessment Guidelines 2024' disagree (one passage permits what the other rules out)."
518
+ },
519
+ {
520
+ "id": "C08",
521
+ "category": "conflicting",
522
+ "question": "What is the penalty for submitting an assignment one day late?",
523
+ "baseline_answer": "Late submissions are accepted for up to 3 calendar days after the deadline with a penalty of 10% of the maximum marks per day. [1] Assignments must be submitted as a single PDF file of no more than 10 MB. [1]",
524
+ "evidenceguard_answer": "\u26a0\ufe0f **Conflicting evidence found.** The documents disagree:\n- *Assignment Submission Policy 2024* (issued 2024-06-10): Late submissions are accepted for up to 3 calendar days after the deadline with a penalty of 10% of the maximum marks per day. [1]\n- *Internal Assessment Guidelines 2024* (issued 2024-05-20): Assignments submitted after the deadline will not be accepted for internal assessment. [6]\nThe more recent document is *Assignment Submission Policy 2024*. Please confirm with the issuing office before relying on either version.\n**Most relevant evidence:** Assignments must be submitted as a single PDF file of no more than 10 MB. [1]",
525
+ "explanation": "Answered with a conflict warning: 'Assignment Submission Policy 2024' and 'Internal Assessment Guidelines 2024' disagree (one passage permits what the other rules out)."
526
+ },
527
+ {
528
+ "id": "C09",
529
+ "category": "conflicting",
530
+ "question": "How many books can a postgraduate student borrow from the library?",
531
+ "baseline_answer": "Postgraduate students may borrow up to 5 books for 14 days. [1] Library hours during examination periods are extended until 12:00 midnight on working days. [2]",
532
+ "evidenceguard_answer": "\u26a0\ufe0f **Conflicting evidence found.** The documents disagree:\n- *Central Library Regulations 2023* (issued 2023-07-01): Postgraduate students may borrow up to 5 books for 14 days. [1]\n- *Library Notice: Revised Borrowing Rules* (issued 2025-07-10): With effect from 1 August 2025, postgraduate students may borrow up to 6 books for a period of 21 days. [2]\nThe more recent document is *Library Notice: Revised Borrowing Rules*, which explicitly revises the earlier rule. Please confirm with the issuing office before relying on either version.\n**Most relevant evidence:** Library hours during examination periods are extended until 12:00 midnight on working days. [2]",
533
+ "explanation": "Answered with a conflict warning: 'Central Library Regulations 2023' and 'Library Notice: Revised Borrowing Rules' disagree (books: 5 vs 6 (context: borrow, day, postgraduate))."
534
+ },
535
+ {
536
+ "id": "C10",
537
+ "category": "conflicting",
538
+ "question": "For how many days can a postgraduate student keep a borrowed library book?",
539
+ "baseline_answer": "Postgraduate students may borrow up to 5 books for 14 days. [2] Reference books cannot be borrowed and must be used within the library. [1]",
540
+ "evidenceguard_answer": "\u26a0\ufe0f **Conflicting evidence found.** The documents disagree:\n- *Library Notice: Revised Borrowing Rules* (issued 2025-07-10): With effect from 1 August 2025, postgraduate students may borrow up to 6 books for a period of 21 days. [2]\n- *Central Library Regulations 2023* (issued 2023-07-01): Postgraduate students may borrow up to 5 books for 14 days. [3]\nThe more recent document is *Library Notice: Revised Borrowing Rules*, which explicitly revises the earlier rule. Please confirm with the issuing office before relying on either version.\n**Most relevant evidence:** Reference books cannot be borrowed and must be used within the library. [1]",
541
+ "explanation": "Answered with a conflict warning: 'Library Notice: Revised Borrowing Rules' and 'Central Library Regulations 2023' disagree (days: 21 vs 14 (context: book, borrow, postgraduate))."
542
+ },
543
+ {
544
+ "id": "C11",
545
+ "category": "conflicting",
546
+ "question": "What is the library overdue fine per book per day?",
547
+ "baseline_answer": "An overdue fine of INR 5 per book per day is charged. [1] Reference books cannot be borrowed and must be used within the library. [1]",
548
+ "evidenceguard_answer": "\u26a0\ufe0f **Conflicting evidence found.** The documents disagree:\n- *Central Library Regulations 2023* (issued 2023-07-01): An overdue fine of INR 5 per book per day is charged. [1]\n- *Library Notice: Revised Borrowing Rules* (issued 2025-07-10): The overdue fine is revised to INR 10 per book per day. [2]\nThe more recent document is *Library Notice: Revised Borrowing Rules*, which explicitly revises the earlier rule. Please confirm with the issuing office before relying on either version.\n**Most relevant evidence:** Reference books cannot be borrowed and must be used within the library. [1]",
549
+ "explanation": "Answered with a conflict warning: 'Central Library Regulations 2023' and 'Library Notice: Revised Borrowing Rules' disagree (inr: 5 vs 10 (context: book, day, fine, overdue))."
550
+ },
551
+ {
552
+ "id": "C12",
553
+ "category": "conflicting",
554
+ "question": "How long is the add/drop period for elective courses?",
555
+ "baseline_answer": "Add/drop period for electives: 7 working days from the start of classes. [2]",
556
+ "evidenceguard_answer": "\u26a0\ufe0f **Conflicting evidence found.** The documents disagree:\n- *Course Registration Guidelines 2025* (issued 2025-06-05): Students may add or drop elective courses within 10 working days from the start of classes. [1]\n- *Academic Calendar 2025-26 (Odd Semester)* (issued 2025-06-15): Add/drop period for electives: 7 working days from the start of classes. [2]\nThe more recent document is *Academic Calendar 2025-26 (Odd Semester)*. Please confirm with the issuing office before relying on either version.",
557
+ "explanation": "Answered with a conflict warning: 'Course Registration Guidelines 2025' and 'Academic Calendar 2025-26 (Odd Semester)' disagree (working days: 10 vs 7 (context: add, class, drop, elective))."
558
+ },
559
+ {
560
+ "id": "C13",
561
+ "category": "conflicting",
562
+ "question": "What minimum aggregate percentage is needed to pass a postgraduate course?",
563
+ "baseline_answer": "PG students must obtain at least 50% marks in aggregate to pass a course. [1] Attendance percentage is the number of contact hours attended divided by the number of contact hours conducted in a course, multiplied by 100. [2] A student must secure a minimum of 75% attendance in each course to be eligible to appear for the end-semester examination of that course. [2]",
564
+ "evidenceguard_answer": "\u26a0\ufe0f **Conflicting evidence found.** The documents disagree:\n- *Postgraduate Programme Handbook 2025-26 (Extract)* (issued 2025-07-05): PG students must obtain at least 50% marks in aggregate to pass a course. [1]\n- *Grading and Academic Progression Policy 2024* (issued 2024-04-02): To pass a course, a student must secure at least 40% marks in aggregate (internal assessment plus end-semester examination) and at least 35% in the end-semester examination (21 out of 60). [4]\nThe more recent document is *Postgraduate Programme Handbook 2025-26 (Extract)*. Please confirm with the issuing office before relying on either version.\n**Most relevant evidence:** Attendance percentage is the number of contact hours attended divided by the number of contact hours conducted in a course, multiplied by 100. [3]",
565
+ "explanation": "Answered with a conflict warning: 'Postgraduate Programme Handbook 2025-26 (Extract)' and 'Grading and Academic Progression Policy 2024' disagree (%: 50 vs 40 (context: aggregate, mark, pass))."
566
+ },
567
+ {
568
+ "id": "C14",
569
+ "category": "conflicting",
570
+ "question": "On what date do the odd semester end-semester examinations begin?",
571
+ "baseline_answer": "The odd semester end-semester examinations commence on 1 December 2025 and conclude on 12 December 2025. [1] Odd semester classes begin on 21 July 2025. [3] Key Dates - Odd Semester 2025-26. [3]",
572
+ "evidenceguard_answer": "\u26a0\ufe0f **Conflicting evidence found.** The documents disagree:\n- *End-Semester Examination Timetable - Odd Semester 2025-26* (issued 2025-10-20): The odd semester end-semester examinations commence on 1 December 2025 and conclude on 12 December 2025. [2]\n- *Academic Calendar 2025-26 (Odd Semester)* (issued 2025-06-15): End-semester examinations: from 3 December 2025. [3]\nThe more recent document is *End-Semester Examination Timetable - Odd Semester 2025-26*. Please confirm with the issuing office before relying on either version.\n**Most relevant evidence:** Odd semester classes begin on 21 July 2025. [1] Key Dates - Odd Semester 2025-26. [1]",
573
+ "explanation": "Answered with a conflict warning: 'End-Semester Examination Timetable - Odd Semester 2025-26' and 'Academic Calendar 2025-26 (Odd Semester)' disagree (date: 12 december 2025 vs 3 december 2025 (context: end-semester, examination))."
574
+ },
575
+ {
576
+ "id": "C15",
577
+ "category": "conflicting",
578
+ "question": "Can I drop an elective course 9 working days after classes start?",
579
+ "baseline_answer": "Students may add or drop elective courses within 10 working days from the start of classes. [1]",
580
+ "evidenceguard_answer": "\u26a0\ufe0f **Conflicting evidence found.** The documents disagree:\n- *Course Registration Guidelines 2025* (issued 2025-06-05): Students may add or drop elective courses within 10 working days from the start of classes. [1]\n- *Academic Calendar 2025-26 (Odd Semester)* (issued 2025-06-15): Add/drop period for electives: 7 working days from the start of classes. [2]\nThe more recent document is *Academic Calendar 2025-26 (Odd Semester)*. Please confirm with the issuing office before relying on either version.",
581
+ "explanation": "Answered with a conflict warning: 'Course Registration Guidelines 2025' and 'Academic Calendar 2025-26 (Odd Semester)' disagree (working days: 10 vs 7 (context: add, class, drop, elective))."
582
+ }
583
+ ]
584
+ }
results/metrics.csv ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ split,configuration,n_questions,precision_at_k,recall_at_k,mrr,answer_correctness,faithfulness,grounded_faithfulness,answer_relevance,context_precision,context_recall,unsupported_answer_rate,abstention_accuracy,abstention_precision,abstention_recall,abstention_f1,abstention_rate,contradiction_precision,contradiction_recall,contradiction_f1,contradiction_accuracy,citation_support_accuracy,behaviour_accuracy,avg_response_time_s,avg_retrieval_time_s,avg_generation_time_s,avg_verification_time_s
2
+ all,Baseline RAG,100,0.4541,0.9647,0.9765,0.57,1.0,0.7567,0.4425,0.9244,0.9765,0.19,0.85,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.8,0.7483,0.55,0.0014,0.0006,0.0007,0.0
3
+ all,+ Reranking,100,0.44,0.9765,0.9588,0.56,1.0,0.735,0.4417,0.9101,0.9824,0.2,0.85,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.8,0.72,0.54,0.0023,0.0017,0.0006,0.0
4
+ all,+ Verification,100,0.4148,0.9765,0.9765,0.73,1.0,0.8311,0.473,0.921,0.9824,0.09,0.83,0.4615,0.8,0.5854,0.26,0.8667,0.65,0.7429,0.91,0.8108,0.73,0.0042,0.001,0.0005,0.0027
5
+ all,EvidenceGuard,100,0.4106,0.9824,0.9588,0.73,1.0,0.8221,0.4744,0.9059,0.9882,0.09,0.83,0.4615,0.8,0.5854,0.26,0.8667,0.65,0.7429,0.91,0.8018,0.73,0.0055,0.0018,0.0005,0.0031
6
+ test,Baseline RAG,71,0.4633,0.975,0.975,0.5634,1.0,0.77,0.4523,0.9279,0.9833,0.2113,0.8451,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.8028,0.7559,0.5352,0.0014,0.0006,0.0007,0.0
7
+ test,+ Reranking,71,0.46,0.9917,0.9583,0.5493,1.0,0.7465,0.4496,0.9154,0.9917,0.2254,0.8451,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.8028,0.73,0.5211,0.0023,0.0017,0.0006,0.0
8
+ test,+ Verification,71,0.4305,0.9833,0.975,0.7042,1.0,0.8576,0.5024,0.9237,0.9833,0.0986,0.8028,0.4348,0.9091,0.5882,0.3239,0.8182,0.6429,0.72,0.9014,0.8264,0.7042,0.004,0.001,0.0005,0.0026
9
+ test,EvidenceGuard,71,0.4347,0.9917,0.9583,0.7042,1.0,0.8438,0.5018,0.915,0.9917,0.0986,0.8028,0.4348,0.9091,0.5882,0.3239,0.8182,0.6429,0.72,0.9014,0.8125,0.7042,0.0052,0.0018,0.0005,0.0029
10
+ dev,Baseline RAG,29,0.432,0.94,0.98,0.5862,1.0,0.7241,0.4185,0.9159,0.96,0.1379,0.8621,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.7931,0.7299,0.5862,0.0013,0.0006,0.0007,0.0
11
+ dev,+ Reranking,29,0.392,0.94,0.96,0.5862,1.0,0.7069,0.4222,0.8973,0.96,0.1379,0.8621,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.7931,0.6954,0.5862,0.0023,0.0016,0.0006,0.0
12
+ dev,+ Verification,29,0.3772,0.96,0.98,0.7931,1.0,0.7821,0.4189,0.9146,0.98,0.069,0.8966,0.6667,0.5,0.5714,0.1034,1.0,0.6667,0.8,0.931,0.7821,0.7931,0.0048,0.0009,0.0007,0.0031
13
+ dev,EvidenceGuard,29,0.3527,0.96,0.96,0.7931,1.0,0.7821,0.4238,0.8839,0.98,0.069,0.8966,0.6667,0.5,0.5714,0.1034,1.0,0.6667,0.8,0.931,0.7821,0.7931,0.0061,0.0017,0.0007,0.0037
results/metrics.json ADDED
@@ -0,0 +1,537 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "meta": {
3
+ "note": "Experiments use SYNTHETIC documents of a fictional university. Results do not establish real-world university policy accuracy.",
4
+ "components": {
5
+ "Embeddings": "LSA (TF-IDF + TruncatedSVD) - offline fallback",
6
+ "Vector store": "FAISS IndexFlatIP (cosine)",
7
+ "Keyword retrieval": "BM25 (rank_bm25) fused with Reciprocal Rank Fusion",
8
+ "Reranker": "Lexical cross-scorer (IDF coverage + bigrams + BM25) - offline fallback",
9
+ "Evidence verifier": "Rule-based verifier (numeric mismatch, polarity flip, lexical support) - offline fallback",
10
+ "Generator": "Extractive composer (no LLM) - offline fallback"
11
+ },
12
+ "backend": "lite",
13
+ "llm_backend": "extractive",
14
+ "thresholds": {
15
+ "min_relevance": 0.15,
16
+ "min_coverage": 0.6,
17
+ "partial_coverage": 0.5,
18
+ "min_confidence": 0.3,
19
+ "conflict_topic_sim": 0.3,
20
+ "conflict_sentence_coverage": 0.35,
21
+ "conflict_min_shared": 2,
22
+ "conflict_subject_mismatch": 0.3,
23
+ "conflict_min_relevance": 0.25,
24
+ "nli_contradiction": 0.6,
25
+ "nli_entailment": 0.5,
26
+ "citation_overlap": 0.5
27
+ },
28
+ "n_questions": 100,
29
+ "dev_questions": 29,
30
+ "test_questions": 71,
31
+ "python": "3.13.18",
32
+ "machine": "x86_64",
33
+ "cpu_count": 2,
34
+ "runtime_s": 23.7,
35
+ "date": "2026-11-19 07:51"
36
+ },
37
+ "metrics": {
38
+ "all": {
39
+ "baseline": {
40
+ "n_questions": 100,
41
+ "precision_at_k": 0.4541,
42
+ "recall_at_k": 0.9647,
43
+ "mrr": 0.9765,
44
+ "answer_correctness": 0.57,
45
+ "faithfulness": 1.0,
46
+ "grounded_faithfulness": 0.7567,
47
+ "answer_relevance": 0.4425,
48
+ "context_precision": 0.9244,
49
+ "context_recall": 0.9765,
50
+ "unsupported_answer_rate": 0.19,
51
+ "abstention_accuracy": 0.85,
52
+ "abstention_precision": 0.0,
53
+ "abstention_recall": 0.0,
54
+ "abstention_f1": 0.0,
55
+ "abstention_rate": 0.0,
56
+ "contradiction_precision": 0.0,
57
+ "contradiction_recall": 0.0,
58
+ "contradiction_f1": 0.0,
59
+ "contradiction_accuracy": 0.8,
60
+ "citation_support_accuracy": 0.7483,
61
+ "behaviour_accuracy": 0.55,
62
+ "avg_response_time_s": 0.0014,
63
+ "avg_retrieval_time_s": 0.0006,
64
+ "avg_generation_time_s": 0.0007,
65
+ "avg_verification_time_s": 0.0
66
+ },
67
+ "rerank": {
68
+ "n_questions": 100,
69
+ "precision_at_k": 0.44,
70
+ "recall_at_k": 0.9765,
71
+ "mrr": 0.9588,
72
+ "answer_correctness": 0.56,
73
+ "faithfulness": 1.0,
74
+ "grounded_faithfulness": 0.735,
75
+ "answer_relevance": 0.4417,
76
+ "context_precision": 0.9101,
77
+ "context_recall": 0.9824,
78
+ "unsupported_answer_rate": 0.2,
79
+ "abstention_accuracy": 0.85,
80
+ "abstention_precision": 0.0,
81
+ "abstention_recall": 0.0,
82
+ "abstention_f1": 0.0,
83
+ "abstention_rate": 0.0,
84
+ "contradiction_precision": 0.0,
85
+ "contradiction_recall": 0.0,
86
+ "contradiction_f1": 0.0,
87
+ "contradiction_accuracy": 0.8,
88
+ "citation_support_accuracy": 0.72,
89
+ "behaviour_accuracy": 0.54,
90
+ "avg_response_time_s": 0.0023,
91
+ "avg_retrieval_time_s": 0.0017,
92
+ "avg_generation_time_s": 0.0006,
93
+ "avg_verification_time_s": 0.0
94
+ },
95
+ "verify": {
96
+ "n_questions": 100,
97
+ "precision_at_k": 0.4148,
98
+ "recall_at_k": 0.9765,
99
+ "mrr": 0.9765,
100
+ "answer_correctness": 0.73,
101
+ "faithfulness": 1.0,
102
+ "grounded_faithfulness": 0.8311,
103
+ "answer_relevance": 0.473,
104
+ "context_precision": 0.921,
105
+ "context_recall": 0.9824,
106
+ "unsupported_answer_rate": 0.09,
107
+ "abstention_accuracy": 0.83,
108
+ "abstention_precision": 0.4615,
109
+ "abstention_recall": 0.8,
110
+ "abstention_f1": 0.5854,
111
+ "abstention_rate": 0.26,
112
+ "contradiction_precision": 0.8667,
113
+ "contradiction_recall": 0.65,
114
+ "contradiction_f1": 0.7429,
115
+ "contradiction_accuracy": 0.91,
116
+ "citation_support_accuracy": 0.8108,
117
+ "behaviour_accuracy": 0.73,
118
+ "avg_response_time_s": 0.0042,
119
+ "avg_retrieval_time_s": 0.001,
120
+ "avg_generation_time_s": 0.0005,
121
+ "avg_verification_time_s": 0.0027
122
+ },
123
+ "full": {
124
+ "n_questions": 100,
125
+ "precision_at_k": 0.4106,
126
+ "recall_at_k": 0.9824,
127
+ "mrr": 0.9588,
128
+ "answer_correctness": 0.73,
129
+ "faithfulness": 1.0,
130
+ "grounded_faithfulness": 0.8221,
131
+ "answer_relevance": 0.4744,
132
+ "context_precision": 0.9059,
133
+ "context_recall": 0.9882,
134
+ "unsupported_answer_rate": 0.09,
135
+ "abstention_accuracy": 0.83,
136
+ "abstention_precision": 0.4615,
137
+ "abstention_recall": 0.8,
138
+ "abstention_f1": 0.5854,
139
+ "abstention_rate": 0.26,
140
+ "contradiction_precision": 0.8667,
141
+ "contradiction_recall": 0.65,
142
+ "contradiction_f1": 0.7429,
143
+ "contradiction_accuracy": 0.91,
144
+ "citation_support_accuracy": 0.8018,
145
+ "behaviour_accuracy": 0.73,
146
+ "avg_response_time_s": 0.0055,
147
+ "avg_retrieval_time_s": 0.0018,
148
+ "avg_generation_time_s": 0.0005,
149
+ "avg_verification_time_s": 0.0031
150
+ }
151
+ },
152
+ "test": {
153
+ "baseline": {
154
+ "n_questions": 71,
155
+ "precision_at_k": 0.4633,
156
+ "recall_at_k": 0.975,
157
+ "mrr": 0.975,
158
+ "answer_correctness": 0.5634,
159
+ "faithfulness": 1.0,
160
+ "grounded_faithfulness": 0.77,
161
+ "answer_relevance": 0.4523,
162
+ "context_precision": 0.9279,
163
+ "context_recall": 0.9833,
164
+ "unsupported_answer_rate": 0.2113,
165
+ "abstention_accuracy": 0.8451,
166
+ "abstention_precision": 0.0,
167
+ "abstention_recall": 0.0,
168
+ "abstention_f1": 0.0,
169
+ "abstention_rate": 0.0,
170
+ "contradiction_precision": 0.0,
171
+ "contradiction_recall": 0.0,
172
+ "contradiction_f1": 0.0,
173
+ "contradiction_accuracy": 0.8028,
174
+ "citation_support_accuracy": 0.7559,
175
+ "behaviour_accuracy": 0.5352,
176
+ "avg_response_time_s": 0.0014,
177
+ "avg_retrieval_time_s": 0.0006,
178
+ "avg_generation_time_s": 0.0007,
179
+ "avg_verification_time_s": 0.0
180
+ },
181
+ "rerank": {
182
+ "n_questions": 71,
183
+ "precision_at_k": 0.46,
184
+ "recall_at_k": 0.9917,
185
+ "mrr": 0.9583,
186
+ "answer_correctness": 0.5493,
187
+ "faithfulness": 1.0,
188
+ "grounded_faithfulness": 0.7465,
189
+ "answer_relevance": 0.4496,
190
+ "context_precision": 0.9154,
191
+ "context_recall": 0.9917,
192
+ "unsupported_answer_rate": 0.2254,
193
+ "abstention_accuracy": 0.8451,
194
+ "abstention_precision": 0.0,
195
+ "abstention_recall": 0.0,
196
+ "abstention_f1": 0.0,
197
+ "abstention_rate": 0.0,
198
+ "contradiction_precision": 0.0,
199
+ "contradiction_recall": 0.0,
200
+ "contradiction_f1": 0.0,
201
+ "contradiction_accuracy": 0.8028,
202
+ "citation_support_accuracy": 0.73,
203
+ "behaviour_accuracy": 0.5211,
204
+ "avg_response_time_s": 0.0023,
205
+ "avg_retrieval_time_s": 0.0017,
206
+ "avg_generation_time_s": 0.0006,
207
+ "avg_verification_time_s": 0.0
208
+ },
209
+ "verify": {
210
+ "n_questions": 71,
211
+ "precision_at_k": 0.4305,
212
+ "recall_at_k": 0.9833,
213
+ "mrr": 0.975,
214
+ "answer_correctness": 0.7042,
215
+ "faithfulness": 1.0,
216
+ "grounded_faithfulness": 0.8576,
217
+ "answer_relevance": 0.5024,
218
+ "context_precision": 0.9237,
219
+ "context_recall": 0.9833,
220
+ "unsupported_answer_rate": 0.0986,
221
+ "abstention_accuracy": 0.8028,
222
+ "abstention_precision": 0.4348,
223
+ "abstention_recall": 0.9091,
224
+ "abstention_f1": 0.5882,
225
+ "abstention_rate": 0.3239,
226
+ "contradiction_precision": 0.8182,
227
+ "contradiction_recall": 0.6429,
228
+ "contradiction_f1": 0.72,
229
+ "contradiction_accuracy": 0.9014,
230
+ "citation_support_accuracy": 0.8264,
231
+ "behaviour_accuracy": 0.7042,
232
+ "avg_response_time_s": 0.004,
233
+ "avg_retrieval_time_s": 0.001,
234
+ "avg_generation_time_s": 0.0005,
235
+ "avg_verification_time_s": 0.0026
236
+ },
237
+ "full": {
238
+ "n_questions": 71,
239
+ "precision_at_k": 0.4347,
240
+ "recall_at_k": 0.9917,
241
+ "mrr": 0.9583,
242
+ "answer_correctness": 0.7042,
243
+ "faithfulness": 1.0,
244
+ "grounded_faithfulness": 0.8438,
245
+ "answer_relevance": 0.5018,
246
+ "context_precision": 0.915,
247
+ "context_recall": 0.9917,
248
+ "unsupported_answer_rate": 0.0986,
249
+ "abstention_accuracy": 0.8028,
250
+ "abstention_precision": 0.4348,
251
+ "abstention_recall": 0.9091,
252
+ "abstention_f1": 0.5882,
253
+ "abstention_rate": 0.3239,
254
+ "contradiction_precision": 0.8182,
255
+ "contradiction_recall": 0.6429,
256
+ "contradiction_f1": 0.72,
257
+ "contradiction_accuracy": 0.9014,
258
+ "citation_support_accuracy": 0.8125,
259
+ "behaviour_accuracy": 0.7042,
260
+ "avg_response_time_s": 0.0052,
261
+ "avg_retrieval_time_s": 0.0018,
262
+ "avg_generation_time_s": 0.0005,
263
+ "avg_verification_time_s": 0.0029
264
+ }
265
+ },
266
+ "dev": {
267
+ "baseline": {
268
+ "n_questions": 29,
269
+ "precision_at_k": 0.432,
270
+ "recall_at_k": 0.94,
271
+ "mrr": 0.98,
272
+ "answer_correctness": 0.5862,
273
+ "faithfulness": 1.0,
274
+ "grounded_faithfulness": 0.7241,
275
+ "answer_relevance": 0.4185,
276
+ "context_precision": 0.9159,
277
+ "context_recall": 0.96,
278
+ "unsupported_answer_rate": 0.1379,
279
+ "abstention_accuracy": 0.8621,
280
+ "abstention_precision": 0.0,
281
+ "abstention_recall": 0.0,
282
+ "abstention_f1": 0.0,
283
+ "abstention_rate": 0.0,
284
+ "contradiction_precision": 0.0,
285
+ "contradiction_recall": 0.0,
286
+ "contradiction_f1": 0.0,
287
+ "contradiction_accuracy": 0.7931,
288
+ "citation_support_accuracy": 0.7299,
289
+ "behaviour_accuracy": 0.5862,
290
+ "avg_response_time_s": 0.0013,
291
+ "avg_retrieval_time_s": 0.0006,
292
+ "avg_generation_time_s": 0.0007,
293
+ "avg_verification_time_s": 0.0
294
+ },
295
+ "rerank": {
296
+ "n_questions": 29,
297
+ "precision_at_k": 0.392,
298
+ "recall_at_k": 0.94,
299
+ "mrr": 0.96,
300
+ "answer_correctness": 0.5862,
301
+ "faithfulness": 1.0,
302
+ "grounded_faithfulness": 0.7069,
303
+ "answer_relevance": 0.4222,
304
+ "context_precision": 0.8973,
305
+ "context_recall": 0.96,
306
+ "unsupported_answer_rate": 0.1379,
307
+ "abstention_accuracy": 0.8621,
308
+ "abstention_precision": 0.0,
309
+ "abstention_recall": 0.0,
310
+ "abstention_f1": 0.0,
311
+ "abstention_rate": 0.0,
312
+ "contradiction_precision": 0.0,
313
+ "contradiction_recall": 0.0,
314
+ "contradiction_f1": 0.0,
315
+ "contradiction_accuracy": 0.7931,
316
+ "citation_support_accuracy": 0.6954,
317
+ "behaviour_accuracy": 0.5862,
318
+ "avg_response_time_s": 0.0023,
319
+ "avg_retrieval_time_s": 0.0016,
320
+ "avg_generation_time_s": 0.0006,
321
+ "avg_verification_time_s": 0.0
322
+ },
323
+ "verify": {
324
+ "n_questions": 29,
325
+ "precision_at_k": 0.3772,
326
+ "recall_at_k": 0.96,
327
+ "mrr": 0.98,
328
+ "answer_correctness": 0.7931,
329
+ "faithfulness": 1.0,
330
+ "grounded_faithfulness": 0.7821,
331
+ "answer_relevance": 0.4189,
332
+ "context_precision": 0.9146,
333
+ "context_recall": 0.98,
334
+ "unsupported_answer_rate": 0.069,
335
+ "abstention_accuracy": 0.8966,
336
+ "abstention_precision": 0.6667,
337
+ "abstention_recall": 0.5,
338
+ "abstention_f1": 0.5714,
339
+ "abstention_rate": 0.1034,
340
+ "contradiction_precision": 1.0,
341
+ "contradiction_recall": 0.6667,
342
+ "contradiction_f1": 0.8,
343
+ "contradiction_accuracy": 0.931,
344
+ "citation_support_accuracy": 0.7821,
345
+ "behaviour_accuracy": 0.7931,
346
+ "avg_response_time_s": 0.0048,
347
+ "avg_retrieval_time_s": 0.0009,
348
+ "avg_generation_time_s": 0.0007,
349
+ "avg_verification_time_s": 0.0031
350
+ },
351
+ "full": {
352
+ "n_questions": 29,
353
+ "precision_at_k": 0.3527,
354
+ "recall_at_k": 0.96,
355
+ "mrr": 0.96,
356
+ "answer_correctness": 0.7931,
357
+ "faithfulness": 1.0,
358
+ "grounded_faithfulness": 0.7821,
359
+ "answer_relevance": 0.4238,
360
+ "context_precision": 0.8839,
361
+ "context_recall": 0.98,
362
+ "unsupported_answer_rate": 0.069,
363
+ "abstention_accuracy": 0.8966,
364
+ "abstention_precision": 0.6667,
365
+ "abstention_recall": 0.5,
366
+ "abstention_f1": 0.5714,
367
+ "abstention_rate": 0.1034,
368
+ "contradiction_precision": 1.0,
369
+ "contradiction_recall": 0.6667,
370
+ "contradiction_f1": 0.8,
371
+ "contradiction_accuracy": 0.931,
372
+ "citation_support_accuracy": 0.7821,
373
+ "behaviour_accuracy": 0.7931,
374
+ "avg_response_time_s": 0.0061,
375
+ "avg_retrieval_time_s": 0.0017,
376
+ "avg_generation_time_s": 0.0007,
377
+ "avg_verification_time_s": 0.0037
378
+ }
379
+ }
380
+ },
381
+ "by_category": {
382
+ "baseline": {
383
+ "answerable": {
384
+ "n": 30,
385
+ "answer_correctness": 1.0,
386
+ "behaviour_accuracy": 1.0,
387
+ "unsupported_rate": 0.0,
388
+ "abstention_rate": 0.0
389
+ },
390
+ "conflicting": {
391
+ "n": 20,
392
+ "answer_correctness": 0.1,
393
+ "behaviour_accuracy": 0.0,
394
+ "unsupported_rate": 0.05,
395
+ "abstention_rate": 0.0
396
+ },
397
+ "misleading": {
398
+ "n": 15,
399
+ "answer_correctness": 0.8,
400
+ "behaviour_accuracy": 0.8,
401
+ "unsupported_rate": 0.1333,
402
+ "abstention_rate": 0.0
403
+ },
404
+ "missing": {
405
+ "n": 15,
406
+ "answer_correctness": 0.0,
407
+ "behaviour_accuracy": 0.0,
408
+ "unsupported_rate": 1.0,
409
+ "abstention_rate": 0.0
410
+ },
411
+ "multi_passage": {
412
+ "n": 20,
413
+ "answer_correctness": 0.65,
414
+ "behaviour_accuracy": 0.65,
415
+ "unsupported_rate": 0.05,
416
+ "abstention_rate": 0.0
417
+ }
418
+ },
419
+ "rerank": {
420
+ "answerable": {
421
+ "n": 30,
422
+ "answer_correctness": 1.0,
423
+ "behaviour_accuracy": 1.0,
424
+ "unsupported_rate": 0.0,
425
+ "abstention_rate": 0.0
426
+ },
427
+ "conflicting": {
428
+ "n": 20,
429
+ "answer_correctness": 0.1,
430
+ "behaviour_accuracy": 0.0,
431
+ "unsupported_rate": 0.05,
432
+ "abstention_rate": 0.0
433
+ },
434
+ "misleading": {
435
+ "n": 15,
436
+ "answer_correctness": 0.8,
437
+ "behaviour_accuracy": 0.8,
438
+ "unsupported_rate": 0.1333,
439
+ "abstention_rate": 0.0
440
+ },
441
+ "missing": {
442
+ "n": 15,
443
+ "answer_correctness": 0.0,
444
+ "behaviour_accuracy": 0.0,
445
+ "unsupported_rate": 1.0,
446
+ "abstention_rate": 0.0
447
+ },
448
+ "multi_passage": {
449
+ "n": 20,
450
+ "answer_correctness": 0.6,
451
+ "behaviour_accuracy": 0.6,
452
+ "unsupported_rate": 0.1,
453
+ "abstention_rate": 0.0
454
+ }
455
+ },
456
+ "verify": {
457
+ "answerable": {
458
+ "n": 30,
459
+ "answer_correctness": 0.9,
460
+ "behaviour_accuracy": 0.9,
461
+ "unsupported_rate": 0.0,
462
+ "abstention_rate": 0.1
463
+ },
464
+ "conflicting": {
465
+ "n": 20,
466
+ "answer_correctness": 0.65,
467
+ "behaviour_accuracy": 0.65,
468
+ "unsupported_rate": 0.05,
469
+ "abstention_rate": 0.2
470
+ },
471
+ "misleading": {
472
+ "n": 15,
473
+ "answer_correctness": 0.7333,
474
+ "behaviour_accuracy": 0.7333,
475
+ "unsupported_rate": 0.1333,
476
+ "abstention_rate": 0.1333
477
+ },
478
+ "missing": {
479
+ "n": 15,
480
+ "answer_correctness": 0.8,
481
+ "behaviour_accuracy": 0.8,
482
+ "unsupported_rate": 0.2,
483
+ "abstention_rate": 0.8
484
+ },
485
+ "multi_passage": {
486
+ "n": 20,
487
+ "answer_correctness": 0.5,
488
+ "behaviour_accuracy": 0.5,
489
+ "unsupported_rate": 0.15,
490
+ "abstention_rate": 0.25
491
+ }
492
+ },
493
+ "full": {
494
+ "answerable": {
495
+ "n": 30,
496
+ "answer_correctness": 0.9,
497
+ "behaviour_accuracy": 0.9,
498
+ "unsupported_rate": 0.0,
499
+ "abstention_rate": 0.1
500
+ },
501
+ "conflicting": {
502
+ "n": 20,
503
+ "answer_correctness": 0.65,
504
+ "behaviour_accuracy": 0.65,
505
+ "unsupported_rate": 0.05,
506
+ "abstention_rate": 0.2
507
+ },
508
+ "misleading": {
509
+ "n": 15,
510
+ "answer_correctness": 0.7333,
511
+ "behaviour_accuracy": 0.7333,
512
+ "unsupported_rate": 0.1333,
513
+ "abstention_rate": 0.1333
514
+ },
515
+ "missing": {
516
+ "n": 15,
517
+ "answer_correctness": 0.8,
518
+ "behaviour_accuracy": 0.8,
519
+ "unsupported_rate": 0.2,
520
+ "abstention_rate": 0.8
521
+ },
522
+ "multi_passage": {
523
+ "n": 20,
524
+ "answer_correctness": 0.5,
525
+ "behaviour_accuracy": 0.5,
526
+ "unsupported_rate": 0.15,
527
+ "abstention_rate": 0.25
528
+ }
529
+ }
530
+ },
531
+ "config_names": {
532
+ "baseline": "Baseline RAG",
533
+ "rerank": "+ Reranking",
534
+ "verify": "+ Verification",
535
+ "full": "EvidenceGuard"
536
+ }
537
+ }
results/per_question_results.csv ADDED
The diff for this file is too large to render. See raw diff
 
results/significance.json ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "behaviour_accuracy|all|baseline_vs_rerank": {
3
+ "n": 100,
4
+ "baseline": 0.55,
5
+ "rerank": 0.54,
6
+ "difference": -0.01,
7
+ "ci95": [
8
+ -0.03,
9
+ 0.0
10
+ ],
11
+ "only_other_true": 0,
12
+ "only_baseline_true": 1,
13
+ "mcnemar_exact_p": 1.0
14
+ },
15
+ "behaviour_accuracy|all|baseline_vs_verify": {
16
+ "n": 100,
17
+ "baseline": 0.55,
18
+ "verify": 0.73,
19
+ "difference": 0.18,
20
+ "ci95": [
21
+ 0.08,
22
+ 0.28
23
+ ],
24
+ "only_other_true": 25,
25
+ "only_baseline_true": 7,
26
+ "mcnemar_exact_p": 0.002102
27
+ },
28
+ "behaviour_accuracy|all|baseline_vs_full": {
29
+ "n": 100,
30
+ "baseline": 0.55,
31
+ "full": 0.73,
32
+ "difference": 0.18,
33
+ "ci95": [
34
+ 0.08,
35
+ 0.28
36
+ ],
37
+ "only_other_true": 25,
38
+ "only_baseline_true": 7,
39
+ "mcnemar_exact_p": 0.002102
40
+ },
41
+ "behaviour_accuracy|test|baseline_vs_rerank": {
42
+ "n": 71,
43
+ "baseline": 0.5352,
44
+ "rerank": 0.5211,
45
+ "difference": -0.0141,
46
+ "ci95": [
47
+ -0.0423,
48
+ 0.0
49
+ ],
50
+ "only_other_true": 0,
51
+ "only_baseline_true": 1,
52
+ "mcnemar_exact_p": 1.0
53
+ },
54
+ "behaviour_accuracy|test|baseline_vs_verify": {
55
+ "n": 71,
56
+ "baseline": 0.5352,
57
+ "verify": 0.7042,
58
+ "difference": 0.169,
59
+ "ci95": [
60
+ 0.0423,
61
+ 0.2958
62
+ ],
63
+ "only_other_true": 19,
64
+ "only_baseline_true": 7,
65
+ "mcnemar_exact_p": 0.028959
66
+ },
67
+ "behaviour_accuracy|test|baseline_vs_full": {
68
+ "n": 71,
69
+ "baseline": 0.5352,
70
+ "full": 0.7042,
71
+ "difference": 0.169,
72
+ "ci95": [
73
+ 0.0423,
74
+ 0.2958
75
+ ],
76
+ "only_other_true": 19,
77
+ "only_baseline_true": 7,
78
+ "mcnemar_exact_p": 0.028959
79
+ },
80
+ "unsupported_answer|all|baseline_vs_rerank": {
81
+ "n": 100,
82
+ "baseline": 0.19,
83
+ "rerank": 0.2,
84
+ "difference": 0.01,
85
+ "ci95": [
86
+ 0.0,
87
+ 0.03
88
+ ],
89
+ "only_other_true": 1,
90
+ "only_baseline_true": 0,
91
+ "mcnemar_exact_p": 1.0
92
+ },
93
+ "unsupported_answer|all|baseline_vs_verify": {
94
+ "n": 100,
95
+ "baseline": 0.19,
96
+ "verify": 0.09,
97
+ "difference": -0.1,
98
+ "ci95": [
99
+ -0.17,
100
+ -0.03
101
+ ],
102
+ "only_other_true": 2,
103
+ "only_baseline_true": 12,
104
+ "mcnemar_exact_p": 0.012939
105
+ },
106
+ "unsupported_answer|all|baseline_vs_full": {
107
+ "n": 100,
108
+ "baseline": 0.19,
109
+ "full": 0.09,
110
+ "difference": -0.1,
111
+ "ci95": [
112
+ -0.17,
113
+ -0.03
114
+ ],
115
+ "only_other_true": 2,
116
+ "only_baseline_true": 12,
117
+ "mcnemar_exact_p": 0.012939
118
+ },
119
+ "unsupported_answer|test|baseline_vs_rerank": {
120
+ "n": 71,
121
+ "baseline": 0.2113,
122
+ "rerank": 0.2254,
123
+ "difference": 0.0141,
124
+ "ci95": [
125
+ 0.0,
126
+ 0.0423
127
+ ],
128
+ "only_other_true": 1,
129
+ "only_baseline_true": 0,
130
+ "mcnemar_exact_p": 1.0
131
+ },
132
+ "unsupported_answer|test|baseline_vs_verify": {
133
+ "n": 71,
134
+ "baseline": 0.2113,
135
+ "verify": 0.0986,
136
+ "difference": -0.1127,
137
+ "ci95": [
138
+ -0.2113,
139
+ -0.0282
140
+ ],
141
+ "only_other_true": 2,
142
+ "only_baseline_true": 10,
143
+ "mcnemar_exact_p": 0.038574
144
+ },
145
+ "unsupported_answer|test|baseline_vs_full": {
146
+ "n": 71,
147
+ "baseline": 0.2113,
148
+ "full": 0.0986,
149
+ "difference": -0.1127,
150
+ "ci95": [
151
+ -0.2113,
152
+ -0.0282
153
+ ],
154
+ "only_other_true": 2,
155
+ "only_baseline_true": 10,
156
+ "mcnemar_exact_p": 0.038574
157
+ }
158
+ }
scripts/build_report.py ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Builds the MSc project report content (reports/report_model.json) from the ACTUAL result files,
3
+ then renders DOCX (scripts/render_report_docx.js) and PDF (LibreOffice). Also refreshes the results
4
+ table in README.md. No number in the report is typed by hand - all are read from results/.
5
+
6
+ Usage: python scripts/build_report.py [--author "Name"] [--usn USN]
7
+ """
8
+ import argparse
9
+ import json
10
+ import subprocess
11
+ import sys
12
+ from collections import Counter
13
+ from pathlib import Path
14
+
15
+ ROOT = Path(__file__).resolve().parents[1]
16
+ sys.path.insert(0, str(ROOT))
17
+ sys.path.insert(0, str(ROOT / "scripts"))
18
+
19
+ from corpus_content import DOCUMENTS # noqa: E402
20
+ from src.research import FOUNDATION, FUTURE, LIMITATIONS, OBJECTIVES, PAPERS, RESEARCH_GAP # noqa: E402
21
+
22
+ RES = ROOT / "results"
23
+ M = json.loads((RES / "metrics.json").read_text())
24
+ SIG = json.loads((RES / "significance.json").read_text())
25
+ CAL = json.loads((RES / "calibrated_thresholds.json").read_text())
26
+ FAIL = json.loads((RES / "failure_cases.json").read_text())
27
+ QS = json.loads((ROOT / "evaluation_data" / "questions.json").read_text())
28
+ ORDER = ["baseline", "rerank", "verify", "full"]
29
+ NAMES = M["config_names"]
30
+ B = [] # blocks
31
+
32
+
33
+ def H1(t): B.append({"t": "h1", "text": t})
34
+ def H2(t): B.append({"t": "h2", "text": t})
35
+ def P(t): B.append({"t": "p", "text": t})
36
+ def BUL(items): B.append({"t": "bullets", "items": list(items)})
37
+ def NUM(items): B.append({"t": "numbers", "items": list(items)})
38
+ def TABLE(header, rows, widths=None, size=8): B.append({"t": "table", "header": header, "rows": rows, "widths": widths, "size": size})
39
+ def IMG(path, w=16, cap=""): B.append({"t": "img", "path": str(path), "width_cm": w, "caption": cap})
40
+ def CAP(t): B.append({"t": "caption", "text": t})
41
+ def BR(): B.append({"t": "pagebreak"})
42
+ def CODE(t): B.append({"t": "code", "text": t})
43
+
44
+
45
+ def plain(t):
46
+ """Strip the app's markdown (bold/italic markers, list dashes, emoji badges) for report tables."""
47
+ import re
48
+ t = re.sub(r"\*{1,2}|(?<!\w)_(?!\w)", "", t.replace("\n", " "))
49
+ return re.sub(r"\s+-\s+", " | ", t.replace("⚠️", "[!]")).strip()
50
+
51
+
52
+ def f(x, d=3):
53
+ return "-" if x is None else f"{x:.{d}f}"
54
+
55
+
56
+ def m(split, cfg, key):
57
+ return M["metrics"][split][cfg][key]
58
+
59
+
60
+ def build(author, usn, programme, institution):
61
+ meta = M["meta"]
62
+ A, T = "all", "test"
63
+ sig_b = SIG["behaviour_accuracy|test|baseline_vs_full"]
64
+ sig_u = SIG["unsupported_answer|test|baseline_vs_full"]
65
+ sig_ba = SIG["behaviour_accuracy|all|baseline_vs_full"]
66
+
67
+ # --------------------------------------------------------------- title page
68
+ B.append({"t": "title", "title": "EvidenceGuard AI",
69
+ "subtitle": "A Reliable University Knowledge Assistant Using Retrieval-Augmented Generation, "
70
+ "Large Language Models and Evidence Verification",
71
+ "lines": ["MSc Project Report - Generative AI and Large Language Models",
72
+ f"Submitted by: {author}" + (f" (USN: {usn})" if usn else ""),
73
+ programme, institution, "Guide: ______________________",
74
+ "November 2026"]})
75
+ BR()
76
+
77
+ # --------------------------------------------------------------- abstract
78
+ H1("Abstract")
79
+ P("Standard retrieval-augmented generation (RAG) assistants answer every question, even when the retrieved "
80
+ "documents do not contain the answer or contain contradictory versions of the same rule. For students asking "
81
+ "about attendance, examination eligibility or scholarship deadlines, a fluent but unsupported answer is a "
82
+ "real risk. This project builds EvidenceGuard AI, a university knowledge assistant that verifies evidence "
83
+ "before answering. It combines hybrid retrieval (FAISS dense vectors fused with BM25 by reciprocal rank "
84
+ "fusion), cross-encoder reranking, an evidence-sufficiency check, a conflict-search retrieval step with "
85
+ "numeric-aware contradiction detection, context-grounded generation, sentence-level citation validation and "
86
+ "confidence-based abstention with natural-language explanations. Because no data was available, a corpus of "
87
+ f"{len(DOCUMENTS)} explicitly fictional university PDFs (28 pages) and a 100-question benchmark with "
88
+ "labelled answerable, multi-passage, missing-information, misleading and conflicting questions were "
89
+ "generated from a single fact base. A four-configuration ablation was run on CPU with offline fallback "
90
+ "components (Hugging Face downloads were unavailable in the build environment). On the 71 held-out test "
91
+ f"questions, EvidenceGuard raised expected-behaviour accuracy from {m(T,'baseline','behaviour_accuracy'):.1%} "
92
+ f"to {m(T,'full','behaviour_accuracy'):.1%} (exact McNemar p = {sig_b['mcnemar_exact_p']:.3f}) and reduced the "
93
+ f"unsupported-answer rate from {m(T,'baseline','unsupported_answer_rate'):.1%} to "
94
+ f"{m(T,'full','unsupported_answer_rate'):.1%} (p = {sig_u['mcnemar_exact_p']:.3f}), detecting conflicting "
95
+ f"evidence with F1 = {m(T,'full','contradiction_f1'):.2f}. The gains come from the verification layer; "
96
+ "reranking alone gave no improvement, and verification costs some over-abstention on answerable "
97
+ "multi-part questions. All results use synthetic data and do not establish accuracy on real university "
98
+ "policies. The system is delivered as a seven-tab Gradio application prepared for Hugging Face Spaces.")
99
+ P("Keywords: retrieval-augmented generation, hallucination, abstention, contradiction detection, citation "
100
+ "verification, natural language inference, FAISS, Gradio.")
101
+ BR()
102
+
103
+ # --------------------------------------------------------------- 1-3
104
+ H1("1. Introduction")
105
+ P("Large language models (LLMs) generate fluent text but can hallucinate. Retrieval-augmented generation "
106
+ "[9] reduces this by conditioning the model on retrieved passages, and it has become the default design for "
107
+ "institutional chatbots. Universities are a natural application: rules on attendance, assessment, "
108
+ "scholarships and libraries are spread across regulations, amendment circulars, notices and handbooks that "
109
+ "change every year. Students frequently ask questions whose answers are missing from the documents, are "
110
+ "split across documents, or have been changed by a newer circular.")
111
+ P("Recent benchmarks show that LLMs inside RAG pipelines struggle exactly here: they rarely refuse when "
112
+ "evidence is missing, integrate several documents poorly and are misled by false or conflicting context [1], "
113
+ "[6], and they still produce claims unsupported by the retrieved text [8]. This project designs, implements "
114
+ "and evaluates a verification layer that addresses these failure modes with free, CPU-friendly components.")
115
+
116
+ H1("2. Problem Statement")
117
+ P("Ordinary LLM systems may generate unsupported answers, hallucinate information or fail to recognise "
118
+ "conflicting documents. The task is to build a university knowledge assistant that retrieves information "
119
+ "from uploaded documents and verifies whether sufficient and consistent evidence exists before generating "
120
+ "an answer, and to measure, against a standard RAG baseline, whether this verification reduces unsupported "
121
+ "answers without unacceptable loss of helpfulness.")
122
+
123
+ H1("3. Research Objectives")
124
+ NUM(OBJECTIVES)
125
+ P("Research questions. RQ1: Does evidence verification reduce unsupported answers compared with standard RAG? "
126
+ "RQ2: Can inter-document conflicts in versioned university rules be detected with training-free components? "
127
+ "RQ3: What is the cost of verification in over-abstention and latency? RQ4: How much do hybrid retrieval and "
128
+ "reranking contribute on their own?")
129
+ BR()
130
+
131
+ # --------------------------------------------------------------- 4 literature
132
+ H1("4. Literature Review")
133
+ P("Papers were identified through targeted searches of AAAI, ICLR, NeurIPS, ACL Anthology and arXiv, and "
134
+ "every bibliographic detail below was verified against the publisher or proceedings page. Eight papers "
135
+ "from 2023-2024 were selected because each addresses one failure mode that EvidenceGuard targets.")
136
+ for i, p in enumerate(PAPERS, 1):
137
+ H2(f"4.{i} {p['title']} ({p['authors'].split(',')[0].split()[-1]} et al., {p['year']})")
138
+ P(f"{p['venue']}. Problem: {p['problem']} Method: {p['method']} Technologies: {p['technologies']} "
139
+ f"Results: {p['results']} Limitations: {p['limitations']}")
140
+ H2("4.9 Literature review table")
141
+ rows = [[f"[{i}] {p['title']} - {p['authors']} ({p['year']}), {p['venue']}",
142
+ p["problem"] + " / " + p["method"], p["results"], p["limitations"], p["gap"], p["ours"]]
143
+ for i, p in enumerate(PAPERS, 1)]
144
+ TABLE(["Paper", "Problem / methodology", "Results", "Limitations", "Research gap", "How EvidenceGuard addresses it"],
145
+ rows, widths=[2.6, 3.0, 2.4, 2.4, 2.2, 3.0], size=7)
146
+ CAP("Table 1. Literature review (technologies are listed in Sections 4.1-4.8).")
147
+ BR()
148
+
149
+ H1("5. Research Gap")
150
+ P(RESEARCH_GAP)
151
+ P("Why this gap is realistic for a student project: all components are pre-trained and free (no fine-tuning), "
152
+ "the corpus and benchmark are generated locally, and the full experiment runs on a laptop CPU.")
153
+
154
+ # --------------------------------------------------------------- 6 methodology
155
+ H1("6. Proposed Methodology")
156
+ NUM(["Data creation: generate a fictional but internally consistent policy corpus with planted conflicts, "
157
+ "superseding circulars, distractors and uncovered topics; derive 100 questions with gold evidence pages.",
158
+ "Baseline (System A): PDF ingestion, cleaning, sentence-aware chunking, Sentence-Transformer embeddings, "
159
+ "FAISS search, LLM generation with source citations.",
160
+ "EvidenceGuard (System B): hybrid retrieval, cross-encoder reranking, sufficiency gate, conflict-search "
161
+ "retrieval and contradiction detection, conflict-aware grounded generation, citation validation, "
162
+ "confidence-based abstention and explanation.",
163
+ f"Calibration: thresholds tuned by grid search on a stratified DEV split ({meta['dev_questions']} "
164
+ f"questions) only; results reported on all 100 and on the {meta['test_questions']} held-out TEST questions.",
165
+ "Ablation: (1) baseline, (2) + hybrid retrieval and reranking, (3) + verification without reranking, "
166
+ "(4) complete EvidenceGuard; paired significance tests (exact McNemar, bootstrap 95% CI)."])
167
+
168
+ H1("7. System Architecture")
169
+ IMG(ROOT / "assets" / "architecture.png", 16.5)
170
+ CAP("Figure 1. EvidenceGuard AI architecture (ingestion layer, System A, System B and user interface).")
171
+ P("The code is modular (src/): document_processor (extraction, cleaning, chunking), embeddings, vector_store "
172
+ "(FAISS + BM25 knowledge base), retrieval (dense, BM25, hybrid RRF), reranker, evidence_verifier, "
173
+ "llm_generator, baseline_rag, enhanced_rag, evaluation and system (factory). Every Hugging Face component "
174
+ "has an offline fallback selected automatically if the model cannot be loaded.")
175
+
176
+ H1("8. Workflow Diagram")
177
+ IMG(ROOT / "assets" / "workflow.png", 12.5)
178
+ CAP("Figure 2. Decision workflow of EvidenceGuard: answered, partial, conflict warning or abstained.")
179
+ BR()
180
+
181
+ # --------------------------------------------------------------- 9 dataset
182
+ H1("9. Dataset Creation Methodology")
183
+ P("No external data was used. The script scripts/generate_dataset.py renders every document from a single "
184
+ "Python fact base (scripts/corpus_content.py) with ReportLab, so facts are consistent by construction. "
185
+ "Each page carries the banner 'SYNTHETIC DEMONSTRATION DATA - fictional university, not a real policy', a "
186
+ "metadata table (document number, version, issue and effective dates) and page numbers.")
187
+ TABLE(["ID", "Document", "Issued", "Pages", "Role in the benchmark"],
188
+ [[d["id"], d["title"], d["issued"], str(len(d["pages"])), d["topic"]] for d in DOCUMENTS],
189
+ widths=[1.0, 7.0, 2.2, 1.2, 4.6], size=7.5)
190
+ CAP("Table 2. Synthetic document collection (Aranya Valley University is fictional).")
191
+ P("Planted conflicts: minimum attendance 75% vs 80%; condonation limit 10% vs 5% and fee INR 500 vs INR 1,000; "
192
+ "scholarship deadline 31 August vs 15 September 2025 and income ceiling INR 6,00,000 vs 8,00,000; late "
193
+ "assignments accepted with a 10%/day penalty vs not accepted; PG borrowing 5 books/14 days/INR 5 fine vs "
194
+ "6 books/21 days/INR 10; add/drop 10 vs 7 working days; PG pass mark 40% vs 50%; examinations starting "
195
+ "1 vs 3 December 2025. A hostel guidelines document acts as a distractor full of look-alike numbers.")
196
+ cats = Counter(q["category"] for q in QS)
197
+ TABLE(["Category", "Questions", "Expected evidence status", "Expected behaviour"],
198
+ [["Answerable", str(cats["answerable"]), "sufficient", "answer with citation"],
199
+ ["Multi-passage", str(cats["multi_passage"]), "sufficient", "combine two passages / documents"],
200
+ ["Missing information", str(cats["missing"]), "insufficient", "abstain"],
201
+ ["Misleading / irrelevant context", str(cats["misleading"]), "sufficient", "correct a false premise or ignore distractors"],
202
+ ["Conflicting", str(cats["conflicting"]), "conflicting", "flag the conflict and present both versions"]],
203
+ widths=[4.0, 2.0, 3.6, 6.4], size=8)
204
+ CAP("Table 3. Evaluation question set (evaluation_data/questions.json and .csv).")
205
+ P("Each question stores the expected answer, the key facts a correct answer must contain, the supporting "
206
+ "document(s) and page(s), the expected evidence status and the expected behaviour. The generator locates "
207
+ "every evidence phrase in the extracted PDF text and refuses to write the dataset if a phrase or key fact "
208
+ "is missing, which guarantees that questions are derived from the PDFs.")
209
+
210
+ # --------------------------------------------------------------- 10 models
211
+ H1("10. Model Selection")
212
+ TABLE(["Role", "Hugging Face model (deployment)", "Why", "Offline fallback (used in reported run)"],
213
+ [["Embeddings", "sentence-transformers/all-MiniLM-L6-v2 (384-d)", "Small, fast on CPU, strong general retrieval [10]",
214
+ "LSA: TF-IDF (1-2 grams) + TruncatedSVD"],
215
+ ["Vector DB", "FAISS IndexFlatIP", "Exact cosine search; corpus is small [11]", "same"],
216
+ ["Keyword", "BM25 (rank_bm25) + RRF", "Exact terms such as 'condonation', codes, dates [12], [13]", "same"],
217
+ ["Reranker", "cross-encoder/ms-marco-MiniLM-L-6-v2", "Joint query-passage scoring [14]", "Lexical cross-scorer (IDF coverage, bigrams, BM25)"],
218
+ ["NLI", "cross-encoder/nli-deberta-v3-xsmall", "Contradiction/entailment probabilities; ~70M params", "Numeric-value and polarity rules"],
219
+ ["LLM", "Qwen/Qwen2.5-0.5B-Instruct (local CPU) or HF Inference API (HF_TOKEN secret)",
220
+ "Free, instruction-tuned, fits free CPU Space", "Extractive composer (no LLM)"]],
221
+ widths=[2.0, 4.6, 4.6, 4.8], size=7.5)
222
+ CAP("Table 4. Model selection. The model licences should be re-checked on each model card before deployment.")
223
+ P("Constraints considered: free CPU Spaces (2 vCPU, 16 GB RAM) make 7B models impractical locally, so the "
224
+ "default local LLM is a 0.5B model and a larger model can be used through the Hugging Face Inference API "
225
+ "with a token stored as a Space secret. No API key is written in code. NLI models are known to be weak at "
226
+ "comparing numbers, which dominate policy text, so contradiction detection always also runs explicit "
227
+ "numeric-value rules.")
228
+ BR()
229
+
230
+ # --------------------------------------------------------------- 11 implementation
231
+ H1("11. Implementation")
232
+ H2("11.1 Ingestion and indexing")
233
+ P("PyMuPDF extracts page text (pypdf fallback). Cleaning removes the synthetic-data banner and footers, "
234
+ "de-hyphenates, and terminates short title-case headings so they do not merge with the next sentence. "
235
+ "Pages are split into sentences and packed into ~70-word chunks with a one-sentence overlap; each chunk keeps "
236
+ "its document, title, page and issue date. The knowledge base builds a FAISS index and a BM25 index and "
237
+ "stores IDF weights used by the verifier. Uploaded PDFs are added (or replaced) at run time.")
238
+ H2("11.2 Evidence sufficiency")
239
+ P("The verifier extracts content words of the question (stop words and generic domain words removed, light "
240
+ "stemming) and weights them by IDF; words that never occur in the corpus get the maximum weight. Coverage is "
241
+ "the average of (a) the weighted share of question terms found in the best single passage and (b) the share "
242
+ "found in the top three passages. Evidence is sufficient if the best passage relevance and the coverage "
243
+ "both exceed calibrated thresholds; partial if slightly below and no question term is absent from the whole "
244
+ "corpus; otherwise the system abstains and lists the missing terms.")
245
+ H2("11.3 Conflict-search retrieval and contradiction detection")
246
+ P("Competing versions of a rule are often outside the top-k (an amendment circular is short and worded "
247
+ "differently). The verifier therefore re-queries the index with the best evidence sentences and adds "
248
+ "passages from other documents as conflict candidates. Sentence pairs from different documents are then "
249
+ "tested: (i) numeric conflict - the same kind of value (%, INR, days, books, dates...) with a different "
250
+ "number, described by overlapping words, of the type the question asks about, where the question words near "
251
+ "the value appear in both sentences and the values differ by less than 5x; (ii) polarity conflict - one "
252
+ "sentence negates a predicate that the other asserts; (iii) NLI contradiction probability above a threshold "
253
+ "(when the NLI model is available). The issue dates identify the newer document and update cues "
254
+ "('revised to', 'supersedes', 'extended to') are reported.")
255
+ H2("11.4 Generation, citation validation and abstention")
256
+ P("The grounded prompt instructs the LLM to use only numbered passages, cite every sentence, reply "
257
+ "INSUFFICIENT_EVIDENCE when the answer is absent, present both versions of conflicts and correct false "
258
+ "premises. Every generated sentence is validated against its cited passage: all numbers must occur in the "
259
+ "passage and token overlap must exceed a threshold, or the NLI model must predict entailment. Unsupported "
260
+ "sentences are removed; if none remain the system abstains. Confidence = 0.4 x relevance + 0.4 x coverage "
261
+ "+ 0.2 x supported-sentence ratio. Each response carries an explanation of the decision.")
262
+ H2("11.5 Gradio application")
263
+ P("Seven tabs: Home dashboard, Upload Documents, AI Assistant (chat with follow-up contextualisation and a "
264
+ "Baseline/EvidenceGuard switch), Evidence Verification, Model Comparison, Evaluation Dashboard (with a "
265
+ "button that re-runs the full evaluation) and About Project. Every button is wired to a working function; "
266
+ "this was verified with 21 automated end-to-end interaction tests (Section 14).")
267
+ for i, (fn, cap) in enumerate([("01_home.png", "Home dashboard with live technology stack"),
268
+ ("03_assistant.png", "AI Assistant: abstention and an answer from a newly uploaded PDF"),
269
+ ("04_verification.png", "Evidence Verification tab for a conflicting attendance question"),
270
+ ("05_comparison.png", "Model Comparison: baseline answers an unanswerable question, EvidenceGuard abstains"),
271
+ ("06_dashboard.png", "Evaluation Dashboard with real metrics")], 3):
272
+ p = ROOT / "docs" / "screenshots" / fn
273
+ if p.exists():
274
+ IMG(p, 15.5)
275
+ CAP(f"Figure {i}. {cap} (actual screenshot of the running application).")
276
+ BR()
277
+
278
+ # --------------------------------------------------------------- 12-13 experimental setup & metrics
279
+ H1("12. Experimental Setup")
280
+ comps = meta["components"]
281
+ BUL([f"Hardware: {meta['cpu_count']} CPU cores ({meta['machine']}), no GPU; Python {meta['python']}.",
282
+ f"Components actually used in the reported run: " + "; ".join(f"{k} = {v}" for k, v in comps.items()) + ".",
283
+ "Reason: Hugging Face model downloads were blocked in the build environment. The Hugging Face path is "
284
+ "implemented and was smoke-tested end-to-end with locally built miniature models, but its metrics must be "
285
+ "produced by re-running scripts/run_evaluation.py --backend full (e.g. on Kaggle or the Space).",
286
+ f"Split: stratified by category, seed 42: {meta['dev_questions']} DEV questions (threshold calibration only) "
287
+ f"and {meta['test_questions']} TEST questions.",
288
+ "Calibrated thresholds: " + ", ".join(f"{k} = {v}" for k, v in CAL["thresholds"].items()
289
+ if k in ("min_relevance", "min_coverage", "partial_coverage", "min_confidence",
290
+ "conflict_sentence_coverage", "conflict_topic_sim")) + ".",
291
+ "Top-k = 5 passages; 20 candidates per retriever before fusion/reranking; RRF k = 60.",
292
+ f"Total runtime of calibration + 4 x 100 questions: {meta['runtime_s']} s."])
293
+
294
+ H1("13. Evaluation Metrics")
295
+ TABLE(["Group", "Metric", "Definition used"],
296
+ [["Retrieval", "Precision@5 / Recall@5 / MRR", "Gold unit = (document, page) of the evidence; computed over the 85 questions with evidence"],
297
+ ["Answer", "Answer correctness", "All key facts present (normalised match) for answerable questions; abstention for missing-information questions"],
298
+ ["Answer", "Expected-behaviour accuracy", "Answer / abstain / flag conflict (with both values) / correct premise, as labelled"],
299
+ ["Answer", "Faithfulness", "Share of answer sentences whose numbers and >=70% of tokens occur in the retrieved context"],
300
+ ["Answer", "Evidence-grounded faithfulness", "Same check against the gold evidence pages only"],
301
+ ["Answer", "Answer relevance", "TF-IDF cosine between question and answer (lexical proxy for RAGAS answer relevance)"],
302
+ ["Answer", "Context precision / recall", "Rank-weighted AP@5 of gold pages / share of key facts present in the context"],
303
+ ["Reliability", "Unsupported answer rate", "Non-abstaining answers to unanswerable questions or containing none of the key facts"],
304
+ ["Reliability", "Abstention accuracy, P/R/F1", "Abstain decision vs. 'missing information' label"],
305
+ ["Reliability", "Contradiction P/R/F1", "Conflict flag vs. 'conflicting' label"],
306
+ ["Reliability", "Citation support accuracy", "Share of cited passages that are gold evidence pages"],
307
+ ["Efficiency", "Response / retrieval / generation time", "Mean wall-clock seconds per question"]],
308
+ widths=[2.2, 4.4, 9.4], size=7.5)
309
+ CAP("Table 5. Metrics. Definitions follow RAGAS [7] and ALCE [4] but are computed deterministically against gold labels.")
310
+ BR()
311
+
312
+ # --------------------------------------------------------------- 14 results
313
+ H1("14. Results")
314
+ P(f"All numbers below are read from results/metrics.json (run of {meta['date']}). "
315
+ "Experiments use synthetic documents of a fictional university and do not establish real-world accuracy.")
316
+ keys = [("precision_at_k", "Precision@5"), ("recall_at_k", "Recall@5"), ("mrr", "MRR"),
317
+ ("answer_correctness", "Answer correctness"), ("behaviour_accuracy", "Expected-behaviour accuracy"),
318
+ ("faithfulness", "Faithfulness (to context)"), ("grounded_faithfulness", "Evidence-grounded faithfulness"),
319
+ ("answer_relevance", "Answer relevance (lexical)"), ("context_precision", "Context precision"),
320
+ ("context_recall", "Context recall"), ("unsupported_answer_rate", "Unsupported answer rate (lower better)"),
321
+ ("abstention_accuracy", "Abstention accuracy"), ("abstention_precision", "Abstention precision"),
322
+ ("abstention_recall", "Abstention recall"), ("abstention_f1", "Abstention F1"),
323
+ ("contradiction_precision", "Contradiction precision"), ("contradiction_recall", "Contradiction recall"),
324
+ ("contradiction_f1", "Contradiction F1"), ("citation_support_accuracy", "Citation support accuracy"),
325
+ ("avg_response_time_s", "Avg response time (s)"), ("avg_retrieval_time_s", "Avg retrieval + rerank time (s)"),
326
+ ("avg_verification_time_s", "Avg verification time (s)"), ("avg_generation_time_s", "Avg generation time (s)")]
327
+ for split, label, tno in ((T, f"held-out TEST split ({meta['test_questions']} questions)", 6), (A, "all 100 questions", 7)):
328
+ rows = [[lab] + [f(m(split, c, k), 4 if "time" in k else 3) for c in ORDER] for k, lab in keys]
329
+ TABLE(["Metric"] + [NAMES[c] for c in ORDER], rows, widths=[5.6, 2.6, 2.6, 2.6, 2.6], size=8)
330
+ CAP(f"Table {tno}. Four-configuration comparison on the {label}.")
331
+ IMG(RES / "charts" / "reliability_comparison.png", 16)
332
+ CAP("Figure 8. Reliability metrics (all 100 questions).")
333
+ IMG(RES / "charts" / "answer_quality_comparison.png", 16)
334
+ CAP("Figure 9. Answer quality metrics (all 100 questions).")
335
+ IMG(RES / "charts" / "retrieval_comparison.png", 16)
336
+ CAP("Figure 10. Retrieval metrics (all 100 questions).")
337
+ IMG(RES / "charts" / "category_breakdown.png", 16)
338
+ CAP("Figure 11. Expected-behaviour accuracy by question category.")
339
+ IMG(RES / "charts" / "response_time.png", 15)
340
+ CAP("Figure 12. Mean time per question.")
341
+ H2("14.1 Statistical significance")
342
+ TABLE(["Comparison (paired)", "Baseline", "EvidenceGuard", "Difference [95% CI]", "Discordant (EG only / base only)", "Exact McNemar p"],
343
+ [[name, f"{s['baseline']:.3f}", f"{s['full']:.3f}", f"{s['difference']:+.3f} [{s['ci95'][0]:+.3f}, {s['ci95'][1]:+.3f}]",
344
+ f"{s['only_other_true']} / {s['only_baseline_true']}", f"{s['mcnemar_exact_p']:.4f}"]
345
+ for name, s in (("Behaviour accuracy - test", sig_b), ("Behaviour accuracy - all", sig_ba),
346
+ ("Unsupported answer - test", sig_u),
347
+ ("Unsupported answer - all", SIG["unsupported_answer|all|baseline_vs_full"]))],
348
+ widths=[4.2, 1.8, 2.2, 3.4, 2.6, 1.8], size=7.5)
349
+ CAP("Table 8. Paired significance tests, baseline vs. complete EvidenceGuard (results/significance.json).")
350
+ rr = SIG["behaviour_accuracy|test|baseline_vs_rerank"]
351
+ P(f"Reranking alone (configuration 2) did not change behaviour accuracy significantly "
352
+ f"({rr['difference']:+.3f}, p = {rr['mcnemar_exact_p']:.2f}).")
353
+ BR()
354
+
355
+ # --------------------------------------------------------------- 15-16
356
+ H1("15. Comparative Analysis")
357
+ cb, cf = M["by_category"]["baseline"], M["by_category"]["full"]
358
+ TABLE(["Category", "n", "Baseline behaviour acc.", "EvidenceGuard behaviour acc.", "Baseline abstention rate", "EvidenceGuard abstention rate"],
359
+ [[c, str(cb[c]["n"]), f(cb[c]["behaviour_accuracy"]), f(cf[c]["behaviour_accuracy"]),
360
+ f(cb[c]["abstention_rate"]), f(cf[c]["abstention_rate"])]
361
+ for c in ["answerable", "multi_passage", "missing", "misleading", "conflicting"]],
362
+ widths=[3.2, 1.0, 3.0, 3.2, 2.8, 2.8], size=8)
363
+ CAP("Table 9. Per-category comparison (all 100 questions).")
364
+ BUL([f"RQ1 - unsupported answers: the baseline answered every missing-information question "
365
+ f"(behaviour accuracy {cb['missing']['behaviour_accuracy']:.2f}); EvidenceGuard abstained correctly on "
366
+ f"{cf['missing']['behaviour_accuracy']:.0%} of them and lowered the overall unsupported-answer rate from "
367
+ f"{m(A,'baseline','unsupported_answer_rate'):.2f} to {m(A,'full','unsupported_answer_rate'):.2f}.",
368
+ f"RQ2 - conflicts: the baseline cannot flag conflicts (F1 = 0 by construction). EvidenceGuard reached "
369
+ f"precision {m(A,'full','contradiction_precision'):.2f} and recall {m(A,'full','contradiction_recall'):.2f}; "
370
+ f"the conflict-search retrieval step was needed for amendment circulars that were not in the top-5.",
371
+ f"RQ3 - cost: answerable accuracy fell from {cb['answerable']['behaviour_accuracy']:.2f} to "
372
+ f"{cf['answerable']['behaviour_accuracy']:.2f} and multi-passage from {cb['multi_passage']['behaviour_accuracy']:.2f} "
373
+ f"to {cf['multi_passage']['behaviour_accuracy']:.2f} because of over-abstention; abstention precision is only "
374
+ f"{m(A,'full','abstention_precision'):.2f}. Mean latency rose from {m(A,'baseline','avg_response_time_s')*1000:.1f} ms "
375
+ f"to {m(A,'full','avg_response_time_s')*1000:.1f} ms with offline components (an LLM would dominate latency).",
376
+ "RQ4 - retrieval: recall@5 was already high for the dense LSA baseline on this small corpus, so hybrid "
377
+ "retrieval and the lexical reranker added little; the improvements come from the verification layer "
378
+ "(configurations 3 and 4 are almost identical).",
379
+ f"Note on abstention accuracy: the baseline's {m(A,'baseline','abstention_accuracy'):.2f} is the majority-class rate "
380
+ "(it never abstains while 85% of questions are answerable); abstention F1 is the informative measure.",
381
+ "Faithfulness to context is 1.0 for all configurations because the offline extractive composer can only copy "
382
+ "retrieved sentences; evidence-grounded faithfulness shows the real difference (sentences taken from the right pages)."])
383
+ IMG(RES / "charts" / "error_analysis.png", 16)
384
+ CAP("Figure 13. Error taxonomy, baseline vs. EvidenceGuard (results/error_analysis.csv).")
385
+ H2("15.1 Failure case examples")
386
+ ex, seen_t = [], Counter()
387
+ for e in FAIL["evidenceguard_failures"]: # diverse: at most 2 per error type
388
+ if seen_t[e["error_type"]] < 2:
389
+ ex.append(e)
390
+ seen_t[e["error_type"]] += 1
391
+ TABLE(["ID", "Question", "Error type", "EvidenceGuard output (truncated)"],
392
+ [[e["id"], e["question"], e["error_type"], plain(e["answer"])[:220]] for e in ex],
393
+ widths=[1.1, 5.0, 3.0, 6.9], size=7)
394
+ CAP("Table 10. Examples of EvidenceGuard failures (full list in results/failure_cases.json).")
395
+ wins, seen_c = [], Counter()
396
+ for w in FAIL["evidenceguard_fixes_over_baseline"]: # one or two per category
397
+ if seen_c[w["category"]] < (2 if w["category"] == "conflicting" else 1):
398
+ wins.append(w)
399
+ seen_c[w["category"]] += 1
400
+ TABLE(["ID", "Question", "Baseline answer", "EvidenceGuard answer"],
401
+ [[w["id"], w["question"], plain(w["baseline_answer"])[:170], plain(w["evidenceguard_answer"])[:170]] for w in wins],
402
+ widths=[1.1, 4.3, 5.3, 5.3], size=7)
403
+ CAP("Table 11. Examples where EvidenceGuard corrected a baseline failure.")
404
+ BR()
405
+
406
+ H1("16. Discussion")
407
+ P("The experiment supports the central claim within its scope: a training-free verification layer can stop a "
408
+ "RAG assistant from answering questions its documents cannot support and can surface conflicting rule "
409
+ "versions instead of silently choosing one. This matches the failure modes reported in RGB [1] and "
410
+ "WikiContradict [6], and turns the post-hoc citation evaluation of ALCE [4] into an in-pipeline filter. The "
411
+ "price is over-abstention, the same trade-off Yoran et al. [5] observed for NLI filtering: when a question "
412
+ "is paraphrased away from the document wording, or needs two passages, coverage drops below the threshold. "
413
+ "A practical deployment should therefore present abstentions as 'not found - please check with the office' "
414
+ "with the retrieved passages visible, which the application does.")
415
+ P("Two results temper the conclusions. First, the behaviour-accuracy gain partly reflects the benchmark design: "
416
+ "conflict questions require a conflict flag that the baseline cannot produce. The unsupported-answer rate, "
417
+ "which does not depend on that design, is the cleaner evidence and is also significant. Second, the rule "
418
+ "components were designed while inspecting failures on the same question set; only thresholds were "
419
+ "calibrated on the DEV split. The test results are therefore optimistic and should be confirmed on new, "
420
+ "independently written questions and on real documents.")
421
+
422
+ H1("17. Limitations")
423
+ BUL(LIMITATIONS)
424
+ H1("18. Future Enhancements")
425
+ BUL(FUTURE)
426
+ H1("19. Conclusion")
427
+ P(f"EvidenceGuard AI demonstrates that evidence verification can be added to a RAG assistant with free, "
428
+ f"CPU-only components. On a synthetic university benchmark it reduced unsupported answers by "
429
+ f"{abs(sig_u['difference']):.1%} absolute on held-out questions, detected conflicting rule versions with F1 "
430
+ f"{m(T,'full','contradiction_f1'):.2f}, and explained every decision, at the cost of some over-abstention. The "
431
+ "complete system - data generator, two RAG systems, verification module, evaluation suite and seven-tab "
432
+ "Gradio application - is reproducible from the repository and prepared for Hugging Face Spaces.")
433
+ BR()
434
+
435
+ # --------------------------------------------------------------- references
436
+ H1("20. References")
437
+ refs = [f"{p['authors']}, \"{p['title']},\" {p['venue']}, {p['year']}. [Online]. Available: {p['link']}"
438
+ for p in PAPERS] + FOUNDATION
439
+ B.append({"t": "refs", "items": refs})
440
+ H1("Appendix A. Reproducing the results")
441
+ CODE("pip install -r requirements.txt\npython scripts/generate_dataset.py # 16 PDFs + 100 questions\n"
442
+ "python scripts/run_evaluation.py --backend lite --llm extractive # this report\n"
443
+ "python scripts/run_evaluation.py --backend full --llm hf_api # HF models (needs HF_TOKEN)\n"
444
+ "python scripts/significance.py\npython -m pytest -q\npython app.py")
445
+
446
+
447
+ def readme_table():
448
+ meta = M["meta"]
449
+ keys = [("recall_at_k", "Recall@5"), ("mrr", "MRR"), ("answer_correctness", "Answer correctness"),
450
+ ("behaviour_accuracy", "Expected-behaviour accuracy"), ("grounded_faithfulness", "Evidence-grounded faithfulness"),
451
+ ("unsupported_answer_rate", "Unsupported answer rate ↓"), ("abstention_f1", "Abstention F1"),
452
+ ("contradiction_f1", "Contradiction F1"), ("citation_support_accuracy", "Citation support accuracy"),
453
+ ("avg_response_time_s", "Avg response time (s)")]
454
+ lines = [f"Held-out TEST split ({meta['test_questions']} questions), backend `{meta['backend']}` "
455
+ f"(offline fallback components), run {meta['date']}:\n",
456
+ "| Metric | " + " | ".join(NAMES[c] for c in ORDER) + " |", "|---|" + "---|" * 4]
457
+ for k, lab in keys:
458
+ lines.append(f"| {lab} | " + " | ".join(f(m('test', c, k), 4 if 'time' in k else 3) for c in ORDER) + " |")
459
+ sb, su = SIG["behaviour_accuracy|test|baseline_vs_full"], SIG["unsupported_answer|test|baseline_vs_full"]
460
+ lines.append(f"\nPaired exact McNemar test, baseline vs EvidenceGuard (test split): behaviour accuracy "
461
+ f"{sb['difference']:+.3f} (p = {sb['mcnemar_exact_p']:.3f}); unsupported answers "
462
+ f"{su['difference']:+.3f} (p = {su['mcnemar_exact_p']:.3f}).")
463
+ return "\n".join(lines)
464
+
465
+
466
+ def main():
467
+ ap = argparse.ArgumentParser()
468
+ ap.add_argument("--author", default="Leeshal Princia Monteiro")
469
+ ap.add_argument("--usn", default="SCA25MSD042")
470
+ ap.add_argument("--programme", default="MSc Data Science, School of Computer Applications")
471
+ ap.add_argument("--institution", default="Dayananda Sagar University, Bengaluru")
472
+ a = ap.parse_args()
473
+ build(a.author, a.usn, a.programme, a.institution)
474
+ out = ROOT / "reports"
475
+ out.mkdir(exist_ok=True)
476
+ (out / "report_model.json").write_text(json.dumps(B, indent=1))
477
+ readme = ROOT / "README.md"
478
+ if readme.exists():
479
+ s = readme.read_text()
480
+ if "<!-- RESULTS_START -->" in s:
481
+ pre, rest = s.split("<!-- RESULTS_START -->", 1)
482
+ post = rest.split("<!-- RESULTS_END -->", 1)[1]
483
+ readme.write_text(pre + "<!-- RESULTS_START -->\n" + readme_table() + "\n<!-- RESULTS_END -->" + post)
484
+ subprocess.run(["node", str(ROOT / "scripts" / "render_report_docx.js"), str(out / "report_model.json"),
485
+ str(out / "project_report.docx")], check=True)
486
+ subprocess.run(["soffice", "--headless", "--convert-to", "pdf", "--outdir", str(out),
487
+ str(out / "project_report.docx")], check=True, capture_output=True)
488
+ print("report written:", out / "project_report.docx", out / "project_report.pdf")
489
+
490
+
491
+ if __name__ == "__main__":
492
+ main()
scripts/corpus_content.py ADDED
@@ -0,0 +1,618 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Content of the SYNTHETIC university document collection used by EvidenceGuard AI.
3
+
4
+ Every document belongs to "Aranya Valley University (AVU)", a FICTIONAL institution.
5
+ Nothing here describes a real university or a real policy. The collection is built
6
+ deliberately to contain:
7
+ * consistent facts that can be answered from one passage,
8
+ * facts that need two passages / two documents,
9
+ * superseded or contradictory versions of the same rule (conflicts C1-C8),
10
+ * topics that are NOT covered anywhere (for abstention tests),
11
+ * a distractor document (hostel guidelines) full of look-alike numbers.
12
+
13
+ Conflicts deliberately planted:
14
+ C1 minimum attendance 75% (Attendance Regs 2023, Exam Eligibility 2024) vs 80% (Circular 2025)
15
+ C2 condonation limit 10% / floor 65% (2023) vs 5% / floor 75% (Circular 2025)
16
+ C3 condonation fee INR 500 (2023) vs INR 1,000 (Circular 2025)
17
+ C4 scholarship deadline 31 Aug 2025 (Policy, Calendar) vs 15 Sep 2025 (Notice)
18
+ income ceiling INR 6,00,000 (Policy) vs INR 8,00,000 (Notice)
19
+ C5 late assignments: 10%/day for 3 days (Assignment Policy) vs not accepted (IA Guidelines)
20
+ C6 PG borrowing 5 books/14 days, fine INR 5 (Library 2023) vs 6 books/21 days, INR 10 (Notice 2025)
21
+ C7 add/drop 10 working days (Registration) vs 7 working days (Calendar)
22
+ C8 pass mark 40% (Grading Policy) vs 50% for PG (PG Handbook)
23
+ C9 exams start 1 Dec 2025 (Timetable) vs 3 Dec 2025 (Calendar)
24
+ """
25
+
26
+ UNIVERSITY = "Aranya Valley University (AVU)"
27
+
28
+ # Each document: id, filename, title, doc_no, issued, effective, version, pages (list of
29
+ # list-of-sections). A section is (heading, [paragraph, ...]). Each inner list = one page.
30
+ DOCUMENTS = [
31
+ # ------------------------------------------------------------------ D01
32
+ {
33
+ "id": "D01",
34
+ "filename": "01_Attendance_Regulations_2023.pdf",
35
+ "title": "Attendance Regulations 2023",
36
+ "doc_no": "AVU/ACAD/ATT/2023",
37
+ "issued": "2023-06-15",
38
+ "effective": "2023-07-01",
39
+ "version": "1.0",
40
+ "topic": "Attendance regulations",
41
+ "pages": [
42
+ [
43
+ ("1. Purpose and Scope", [
44
+ "These regulations set out the attendance requirements for all undergraduate and "
45
+ "postgraduate programmes offered by Aranya Valley University. They apply to every "
46
+ "theory, laboratory and tutorial course in which a student is registered.",
47
+ "The regulations are issued by the Office of the Dean of Academics and are binding "
48
+ "on students, course instructors and Heads of Department.",
49
+ ]),
50
+ ("2. Definitions", [
51
+ "A contact hour is one scheduled hour of lecture, tutorial or laboratory work. "
52
+ "Attendance percentage is the number of contact hours attended divided by the number "
53
+ "of contact hours conducted in a course, multiplied by 100.",
54
+ ]),
55
+ ("3. Minimum Attendance Requirement", [
56
+ "A student must secure a minimum of 75% attendance in each course to be eligible to "
57
+ "appear for the end-semester examination of that course.",
58
+ "Attendance is calculated separately for every course and is not averaged across courses.",
59
+ ]),
60
+ ("4. Condonation of Shortage", [
61
+ "The Dean of Academics may condone a shortage of attendance of up to 10% (that is, "
62
+ "attendance between 65% and 75%) on documented medical grounds.",
63
+ "A condonation fee of INR 500 per course is payable before the condonation order is issued.",
64
+ ]),
65
+ ],
66
+ [
67
+ ("5. Recording and Publication of Attendance", [
68
+ "Faculty must upload attendance to the AVU-Learn portal within 48 hours of each class.",
69
+ "The list of students with attendance shortage is published 7 days before the "
70
+ "commencement of end-semester examinations.",
71
+ ]),
72
+ ("6. Consequences of Shortage", [
73
+ "A student who fails to meet the requirement after condonation will be marked NE "
74
+ "(Not Eligible) and must re-register for the course in a subsequent semester.",
75
+ ]),
76
+ ("7. Approved Absences", [
77
+ "Participation in university-approved events such as sports, cultural festivals and NCC "
78
+ "camps is counted as present for up to 10 contact hours per semester, with prior approval "
79
+ "of the Head of Department.",
80
+ ]),
81
+ ("8. Review", [
82
+ "These regulations will be reviewed by the Academic Council every two years.",
83
+ "Issued by: Office of the Dean of Academics, Aranya Valley University (fictional).",
84
+ ]),
85
+ ],
86
+ ],
87
+ },
88
+ # ------------------------------------------------------------------ D02
89
+ {
90
+ "id": "D02",
91
+ "filename": "02_Circular_Attendance_Amendment_2025.pdf",
92
+ "title": "Circular: Amendment to Attendance Regulations",
93
+ "doc_no": "AVU/CIRC/2025/014",
94
+ "issued": "2025-06-02",
95
+ "effective": "2025-07-01",
96
+ "version": "2.0 (amendment)",
97
+ "topic": "Attendance regulations",
98
+ "pages": [
99
+ [
100
+ ("Subject", [
101
+ "Amendment to clauses 3 and 4 of the Attendance Regulations 2023 (AVU/ACAD/ATT/2023).",
102
+ ]),
103
+ ("Revised Provisions", [
104
+ "With effect from the academic year 2025-26, the minimum attendance requirement for each "
105
+ "course is revised to 80%.",
106
+ "Condonation on medical grounds is limited to 5% (that is, attendance between 75% and 80%).",
107
+ "The condonation fee is revised to INR 1,000 per course.",
108
+ ]),
109
+ ("Applicability", [
110
+ "This circular supersedes clauses 3 and 4 of the Attendance Regulations 2023. All other "
111
+ "provisions of the Attendance Regulations 2023 remain unchanged.",
112
+ "Heads of Department are requested to bring this circular to the notice of all students "
113
+ "at the start of the academic year.",
114
+ "Issued by: Registrar, Aranya Valley University (fictional), 2 June 2025.",
115
+ ]),
116
+ ],
117
+ ],
118
+ },
119
+ # ------------------------------------------------------------------ D03
120
+ {
121
+ "id": "D03",
122
+ "filename": "03_Examination_Eligibility_Rules_2024.pdf",
123
+ "title": "Examination Eligibility Rules 2024",
124
+ "doc_no": "AVU/EXAM/ELG/2024",
125
+ "issued": "2024-01-02",
126
+ "effective": "2024-01-15",
127
+ "version": "1.0",
128
+ "topic": "Examination eligibility",
129
+ "pages": [
130
+ [
131
+ ("1. Scope", [
132
+ "These rules determine whether a student may appear for the end-semester examination "
133
+ "of a course. They are administered by the Controller of Examinations.",
134
+ ]),
135
+ ("2. Conditions of Eligibility", [
136
+ "To be eligible for the end-semester examination, a student must satisfy all of the following conditions.",
137
+ "(a) The student must satisfy the attendance requirement of 75% in the course as per the Attendance Regulations.",
138
+ "(b) The student must secure at least 40% of the internal assessment marks in the course, "
139
+ "that is, at least 16 out of 40.",
140
+ "(c) The student must have no outstanding tuition fee dues.",
141
+ "(d) The student must have registered for the course in the current semester.",
142
+ ]),
143
+ ("3. Hall Tickets", [
144
+ "Hall tickets are issued through the AVU-Learn portal 5 days before the first examination.",
145
+ "A student who is not eligible will not be issued a hall ticket for that course.",
146
+ ]),
147
+ ],
148
+ [
149
+ ("4. Appeals", [
150
+ "A student may appeal against an eligibility decision to the Controller of Examinations "
151
+ "within 3 working days of the publication of the eligibility list.",
152
+ ]),
153
+ ("5. Library and Other Dues", [
154
+ "Library dues do not affect examination eligibility but must be cleared before results are released.",
155
+ ]),
156
+ ("6. Students Not Eligible", [
157
+ "Students declared not eligible must re-register for the course when it is next offered "
158
+ "and satisfy all eligibility conditions afresh.",
159
+ "Issued by: Controller of Examinations, Aranya Valley University (fictional).",
160
+ ]),
161
+ ],
162
+ ],
163
+ },
164
+ # ------------------------------------------------------------------ D04
165
+ {
166
+ "id": "D04",
167
+ "filename": "04_Internal_Assessment_Guidelines_2024.pdf",
168
+ "title": "Internal Assessment Guidelines 2024",
169
+ "doc_no": "AVU/ACAD/IA/2024",
170
+ "issued": "2024-05-20",
171
+ "effective": "2024-07-01",
172
+ "version": "1.0",
173
+ "topic": "Internal assessment",
174
+ "pages": [
175
+ [
176
+ ("1. Mark Distribution", [
177
+ "Each theory course carries 100 marks: 40 marks for internal assessment (IA) and 60 marks "
178
+ "for the end-semester examination.",
179
+ ]),
180
+ ("2. Components of Internal Assessment", [
181
+ "Internal assessment consists of Internal Test 1 (15 marks), Internal Test 2 (15 marks), "
182
+ "Assignment (5 marks), and Class participation and quizzes (5 marks).",
183
+ "Internal tests are of 60 minutes duration and are conducted in the 7th and 13th weeks of the semester.",
184
+ ]),
185
+ ("3. Make-up Tests", [
186
+ "A student who misses an internal test on medical grounds may take one make-up test per "
187
+ "semester, provided a medical certificate is submitted within 3 working days of the missed test.",
188
+ ]),
189
+ ],
190
+ [
191
+ ("4. Assignments", [
192
+ "Assignments submitted after the deadline will not be accepted for internal assessment.",
193
+ "Instructors must announce assignment topics at least two weeks before the due date.",
194
+ ]),
195
+ ("5. Publication and Review of Marks", [
196
+ "IA marks are published on AVU-Learn within 10 working days of each test.",
197
+ "Students may request a review of IA marks within 5 working days of publication.",
198
+ ]),
199
+ ("6. Records", [
200
+ "Answer scripts of internal tests are retained by the department for one year.",
201
+ "Issued by: Office of the Dean of Academics, Aranya Valley University (fictional).",
202
+ ]),
203
+ ],
204
+ ],
205
+ },
206
+ # ------------------------------------------------------------------ D05
207
+ {
208
+ "id": "D05",
209
+ "filename": "05_Assignment_Submission_Policy_2024.pdf",
210
+ "title": "Assignment Submission Policy 2024",
211
+ "doc_no": "AVU/ACAD/ASN/2024",
212
+ "issued": "2024-06-10",
213
+ "effective": "2024-07-01",
214
+ "version": "1.0",
215
+ "topic": "Assignment submission",
216
+ "pages": [
217
+ [
218
+ ("1. Mode of Submission", [
219
+ "All assignments must be submitted through the AVU-Learn portal by 11:59 PM on the due date.",
220
+ "Email submissions are not accepted unless the portal is down, as confirmed by the IT Helpdesk.",
221
+ "Assignments must be submitted as a single PDF file of no more than 10 MB.",
222
+ ]),
223
+ ("2. Late Submission", [
224
+ "Late submissions are accepted for up to 3 calendar days after the deadline with a penalty "
225
+ "of 10% of the maximum marks per day.",
226
+ "Submissions received more than 3 days late receive zero marks.",
227
+ ]),
228
+ ("3. Extensions", [
229
+ "Extensions of up to 5 days may be granted by the course instructor on medical or "
230
+ "compassionate grounds if requested before the deadline.",
231
+ ]),
232
+ ],
233
+ [
234
+ ("4. Academic Integrity", [
235
+ "Every submission is checked with the university similarity checker.",
236
+ "A similarity index above 20% requires resubmission within 3 days.",
237
+ "A similarity index above 40% results in zero marks and referral to the Academic Integrity Committee.",
238
+ ]),
239
+ ("5. Group Assignments", [
240
+ "Group assignments may have at most 4 members, and each member must state their individual contribution.",
241
+ "Issued by: Office of the Dean of Academics, Aranya Valley University (fictional).",
242
+ ]),
243
+ ],
244
+ ],
245
+ },
246
+ # ------------------------------------------------------------------ D06
247
+ {
248
+ "id": "D06",
249
+ "filename": "06_Examination_Timetable_Odd_Semester_2025.pdf",
250
+ "title": "End-Semester Examination Timetable - Odd Semester 2025-26",
251
+ "doc_no": "AVU/EXAM/TT/2025/ODD",
252
+ "issued": "2025-10-20",
253
+ "effective": "2025-10-20",
254
+ "version": "1.0",
255
+ "topic": "Examination timetable",
256
+ "pages": [
257
+ [
258
+ ("1. Examination Period", [
259
+ "The odd semester end-semester examinations commence on 1 December 2025 and conclude on 12 December 2025.",
260
+ "Morning session: 10:00 AM to 1:00 PM. Afternoon session: 2:00 PM to 5:00 PM.",
261
+ "Students must report 30 minutes before the start of the session. No student is admitted "
262
+ "more than 30 minutes after the start of the session.",
263
+ ]),
264
+ ("2. MSc Data Science - Semester 3", [
265
+ "01 December 2025 (Monday): MDS301 Deep Learning - Morning session.",
266
+ "03 December 2025 (Wednesday): MDS302 Generative AI and LLMs - Morning session.",
267
+ "05 December 2025 (Friday): MDS303 Advanced Algorithms and Optimisation - Morning session.",
268
+ "08 December 2025 (Monday): MDS304 Information Systems Engineering - Morning session.",
269
+ "10 December 2025 (Wednesday): MDS305 Security for Data Science - Afternoon session.",
270
+ ]),
271
+ ],
272
+ [
273
+ ("3. MBA - Semester 3", [
274
+ "02 December 2025 (Tuesday): MBA301 Financial Management - Morning session.",
275
+ "04 December 2025 (Thursday): MBA302 Marketing Analytics - Afternoon session.",
276
+ "09 December 2025 (Tuesday): MBA303 Strategic Management - Morning session.",
277
+ ]),
278
+ ("4. BSc Computer Science - Semester 5", [
279
+ "01 December 2025 (Monday): BCS501 Operating Systems - Afternoon session.",
280
+ "04 December 2025 (Thursday): BCS502 Computer Networks - Morning session.",
281
+ "11 December 2025 (Thursday): BCS503 Software Engineering - Morning session.",
282
+ ]),
283
+ ("5. General Instructions", [
284
+ "Only non-programmable scientific calculators are permitted in the examination hall.",
285
+ "Results of the odd semester examinations will be announced by 15 January 2026.",
286
+ "Issued by: Controller of Examinations, Aranya Valley University (fictional), 20 October 2025.",
287
+ ]),
288
+ ],
289
+ ],
290
+ },
291
+ # ------------------------------------------------------------------ D07
292
+ {
293
+ "id": "D07",
294
+ "filename": "07_Scholarship_Policy_2025-26.pdf",
295
+ "title": "Scholarship Policy 2025-26",
296
+ "doc_no": "AVU/SCH/2025",
297
+ "issued": "2025-05-01",
298
+ "effective": "2025-05-01",
299
+ "version": "1.0",
300
+ "topic": "Scholarship eligibility",
301
+ "pages": [
302
+ [
303
+ ("1. Merit Scholarship", [
304
+ "Students with a CGPA of 9.0 or above in the previous academic year receive a 50% tuition fee waiver.",
305
+ "Students with a CGPA between 8.5 and 8.99 receive a 25% tuition fee waiver.",
306
+ ]),
307
+ ("2. Need-based Scholarship", [
308
+ "A need-based scholarship of INR 30,000 per year is available to students whose annual "
309
+ "family income does not exceed INR 6,00,000.",
310
+ "Applicants must submit an income certificate issued by a competent authority within the "
311
+ "last 6 months and the marks card of the previous year.",
312
+ ]),
313
+ ("3. Application", [
314
+ "Applications must be submitted on AVU-Learn by 31 August 2025.",
315
+ ]),
316
+ ],
317
+ [
318
+ ("4. Conditions", [
319
+ "A student may hold only one university scholarship at a time; if eligible for more than one, "
320
+ "the higher-value scholarship is awarded.",
321
+ "Students may simultaneously hold one external (government or private) scholarship.",
322
+ "Scholarship holders must maintain a minimum of 75% attendance in every course.",
323
+ ]),
324
+ ("5. Renewal", [
325
+ "Scholarships are renewed annually subject to a CGPA of at least 8.0 and no disciplinary action.",
326
+ "Issued by: Scholarship Cell, Aranya Valley University (fictional), 1 May 2025.",
327
+ ]),
328
+ ],
329
+ ],
330
+ },
331
+ # ------------------------------------------------------------------ D08
332
+ {
333
+ "id": "D08",
334
+ "filename": "08_Scholarship_Revised_Notice_2025.pdf",
335
+ "title": "Notice: Revision of Scholarship Deadline and Income Ceiling",
336
+ "doc_no": "AVU/SCH/NOT/2025/07",
337
+ "issued": "2025-08-25",
338
+ "effective": "2025-08-25",
339
+ "version": "1.1 (notice)",
340
+ "topic": "Scholarship eligibility",
341
+ "pages": [
342
+ [
343
+ ("Notice", [
344
+ "The last date for scholarship applications for 2025-26 is extended to 15 September 2025.",
345
+ "The family income ceiling for the need-based scholarship is revised to INR 8,00,000.",
346
+ "All other conditions of the Scholarship Policy 2025-26 remain unchanged.",
347
+ "Issued by: Scholarship Cell, Aranya Valley University (fictional), 25 August 2025.",
348
+ ]),
349
+ ],
350
+ ],
351
+ },
352
+ # ------------------------------------------------------------------ D09
353
+ {
354
+ "id": "D09",
355
+ "filename": "09_Course_Registration_Guidelines_2025.pdf",
356
+ "title": "Course Registration Guidelines 2025",
357
+ "doc_no": "AVU/ACAD/REG/2025",
358
+ "issued": "2025-06-05",
359
+ "effective": "2025-07-01",
360
+ "version": "1.0",
361
+ "topic": "Course registration",
362
+ "pages": [
363
+ [
364
+ ("1. Registration Window", [
365
+ "Course registration for the odd semester opens on 1 July 2025 and closes on 15 July 2025.",
366
+ "Late registration is permitted until 22 July 2025 with a late fee of INR 2,000.",
367
+ "Registration requires clearance of previous semester fees and approval of the faculty advisor.",
368
+ ]),
369
+ ("2. Credit Limits", [
370
+ "PG students must register for a minimum of 18 and a maximum of 26 credits per semester.",
371
+ "Audit courses do not count toward credit limits.",
372
+ "A student may register for a maximum of 2 open electives per semester.",
373
+ ]),
374
+ ],
375
+ [
376
+ ("3. Add and Drop", [
377
+ "Students may add or drop elective courses within 10 working days from the start of classes.",
378
+ "Core courses cannot be dropped.",
379
+ ]),
380
+ ("4. Prerequisites", [
381
+ "A student may register for a course only after passing its prerequisite courses, as listed in the programme structure.",
382
+ "Issued by: Office of the Dean of Academics, Aranya Valley University (fictional).",
383
+ ]),
384
+ ],
385
+ ],
386
+ },
387
+ # ------------------------------------------------------------------ D10
388
+ {
389
+ "id": "D10",
390
+ "filename": "10_Academic_Leave_Policy_2024.pdf",
391
+ "title": "Academic Leave Policy 2024",
392
+ "doc_no": "AVU/ACAD/LV/2024",
393
+ "issued": "2024-03-11",
394
+ "effective": "2024-07-01",
395
+ "version": "1.0",
396
+ "topic": "Academic leave",
397
+ "pages": [
398
+ [
399
+ ("1. Leave of Absence", [
400
+ "A student may apply for academic leave (leave of absence) for a maximum of two semesters "
401
+ "during the entire programme.",
402
+ "Applications must be submitted to the Dean of Academics at least 30 days before the start of "
403
+ "the semester, except in medical emergencies.",
404
+ "Students may avail maternity leave of up to 6 months, which is counted within the academic leave limit.",
405
+ ]),
406
+ ("2. Medical Leave", [
407
+ "Medical leave of up to 15 days within a semester may be approved by the Head of Department on "
408
+ "submission of a medical certificate from a registered medical practitioner.",
409
+ "Approved medical leave does not count as attendance; it is considered only for condonation.",
410
+ ]),
411
+ ],
412
+ [
413
+ ("3. Fees During Leave", [
414
+ "Students on academic leave are not charged tuition fees for the leave semester but must pay a "
415
+ "registration retention fee of INR 5,000 per semester.",
416
+ ]),
417
+ ("4. Duration and Return", [
418
+ "The maximum duration to complete a programme is the normal duration plus two years, including any academic leave.",
419
+ "Students returning from leave must re-register within the regular registration window.",
420
+ "Issued by: Office of the Dean of Academics, Aranya Valley University (fictional).",
421
+ ]),
422
+ ],
423
+ ],
424
+ },
425
+ # ------------------------------------------------------------------ D11
426
+ {
427
+ "id": "D11",
428
+ "filename": "11_Library_Regulations_2023.pdf",
429
+ "title": "Central Library Regulations 2023",
430
+ "doc_no": "AVU/LIB/2023",
431
+ "issued": "2023-07-01",
432
+ "effective": "2023-07-01",
433
+ "version": "1.0",
434
+ "topic": "Library regulations",
435
+ "pages": [
436
+ [
437
+ ("1. Library Hours", [
438
+ "The Central Library is open from 8:00 AM to 10:00 PM on working days and from 9:00 AM to "
439
+ "5:00 PM on Saturdays. It remains closed on Sundays and university holidays.",
440
+ "A valid university ID card is mandatory for entry.",
441
+ ]),
442
+ ("2. Borrowing Limits", [
443
+ "Undergraduate students may borrow up to 3 books for 14 days.",
444
+ "Postgraduate students may borrow up to 5 books for 14 days.",
445
+ "Research scholars may borrow up to 8 books for 30 days.",
446
+ ]),
447
+ ],
448
+ [
449
+ ("3. Renewal and Reference Books", [
450
+ "A borrowed book may be renewed once if it has not been reserved by another member.",
451
+ "Reference books cannot be borrowed and must be used within the library.",
452
+ ]),
453
+ ("4. Fines and Losses", [
454
+ "An overdue fine of INR 5 per book per day is charged.",
455
+ "Lost books must be replaced or paid for at twice the current price.",
456
+ ]),
457
+ ("5. Electronic Resources", [
458
+ "Subscribed e-journals can be accessed off campus through the library remote access service using university credentials.",
459
+ "Issued by: University Librarian, Aranya Valley University (fictional).",
460
+ ]),
461
+ ],
462
+ ],
463
+ },
464
+ # ------------------------------------------------------------------ D12
465
+ {
466
+ "id": "D12",
467
+ "filename": "12_Library_Notice_2025.pdf",
468
+ "title": "Library Notice: Revised Borrowing Rules",
469
+ "doc_no": "AVU/LIB/NOT/2025/03",
470
+ "issued": "2025-07-10",
471
+ "effective": "2025-08-01",
472
+ "version": "2.0 (notice)",
473
+ "topic": "Library regulations",
474
+ "pages": [
475
+ [
476
+ ("Notice", [
477
+ "With effect from 1 August 2025, postgraduate students may borrow up to 6 books for a period of 21 days.",
478
+ "The overdue fine is revised to INR 10 per book per day.",
479
+ "Library hours during examination periods are extended until 12:00 midnight on working days.",
480
+ "Issued by: University Librarian, Aranya Valley University (fictional), 10 July 2025.",
481
+ ]),
482
+ ],
483
+ ],
484
+ },
485
+ # ------------------------------------------------------------------ D13
486
+ {
487
+ "id": "D13",
488
+ "filename": "13_Grading_and_Academic_Progression_Policy_2024.pdf",
489
+ "title": "Grading and Academic Progression Policy 2024",
490
+ "doc_no": "AVU/ACAD/GRD/2024",
491
+ "issued": "2024-04-02",
492
+ "effective": "2024-07-01",
493
+ "version": "1.0",
494
+ "topic": "Grading and academic progression",
495
+ "pages": [
496
+ [
497
+ ("1. Grading Scale", [
498
+ "Grades are awarded on a 10-point scale as follows.",
499
+ "Grade O (grade point 10): 90 to 100 marks. Grade A+ (grade point 9): 80 to 89 marks. "
500
+ "Grade A (grade point 8): 70 to 79 marks. Grade B+ (grade point 7): 60 to 69 marks. "
501
+ "Grade B (grade point 6): 50 to 59 marks. Grade C (grade point 5): 40 to 49 marks. "
502
+ "Grade F (grade point 0): below 40 marks.",
503
+ ]),
504
+ ("2. Passing a Course", [
505
+ "To pass a course, a student must secure at least 40% marks in aggregate (internal assessment "
506
+ "plus end-semester examination) and at least 35% in the end-semester examination (21 out of 60).",
507
+ ]),
508
+ ("3. SGPA and CGPA", [
509
+ "SGPA is the credit-weighted average of grade points in a semester; CGPA is the credit-weighted "
510
+ "average of grade points over all completed semesters.",
511
+ ]),
512
+ ],
513
+ [
514
+ ("4. Progression", [
515
+ "A student with more than 4 backlog courses at the end of an academic year will not be promoted to the next year.",
516
+ "Supplementary examinations are held in June and July; the maximum grade awarded in a supplementary examination is grade A.",
517
+ ]),
518
+ ("5. Classification", [
519
+ "First Class with Distinction is awarded for a CGPA of 8.0 or above. First Class is awarded for a "
520
+ "CGPA from 6.5 to 7.99. Second Class is awarded for a CGPA from 5.5 to 6.49.",
521
+ "Issued by: Controller of Examinations, Aranya Valley University (fictional).",
522
+ ]),
523
+ ],
524
+ ],
525
+ },
526
+ # ------------------------------------------------------------------ D14
527
+ {
528
+ "id": "D14",
529
+ "filename": "14_Academic_Calendar_2025-26.pdf",
530
+ "title": "Academic Calendar 2025-26 (Odd Semester)",
531
+ "doc_no": "AVU/CAL/2025-26",
532
+ "issued": "2025-06-15",
533
+ "effective": "2025-07-01",
534
+ "version": "1.0",
535
+ "topic": "Academic calendar",
536
+ "pages": [
537
+ [
538
+ ("1. Key Dates - Odd Semester 2025-26", [
539
+ "Odd semester classes begin on 21 July 2025.",
540
+ "Add/drop period for electives: 7 working days from the start of classes.",
541
+ "Last date for scholarship applications: 31 August 2025.",
542
+ "Internal Test 1: 1 September 2025 to 5 September 2025.",
543
+ "Internal Test 2: 13 October 2025 to 17 October 2025.",
544
+ "Last working day of the odd semester: 21 November 2025.",
545
+ "End-semester examinations: from 3 December 2025.",
546
+ ]),
547
+ ],
548
+ [
549
+ ("2. Holidays", [
550
+ "Ganesh Chaturthi: 27 August 2025. Gandhi Jayanti: 2 October 2025. Deepavali: 20 and 21 October 2025.",
551
+ ]),
552
+ ("3. Even Semester", [
553
+ "Even semester classes begin on 5 January 2026.",
554
+ "Issued by: Office of the Dean of Academics, Aranya Valley University (fictional), 15 June 2025.",
555
+ ]),
556
+ ],
557
+ ],
558
+ },
559
+ # ------------------------------------------------------------------ D15
560
+ {
561
+ "id": "D15",
562
+ "filename": "15_PG_Programme_Handbook_Extract_2025.pdf",
563
+ "title": "Postgraduate Programme Handbook 2025-26 (Extract)",
564
+ "doc_no": "AVU/PG/HB/2025",
565
+ "issued": "2025-07-05",
566
+ "effective": "2025-07-21",
567
+ "version": "1.0",
568
+ "topic": "Grading and academic progression",
569
+ "pages": [
570
+ [
571
+ ("1. About this Handbook", [
572
+ "This handbook summarises key academic rules for postgraduate (PG) students. Where it differs "
573
+ "from a university regulation, students should seek clarification from the Dean of Academics.",
574
+ ]),
575
+ ("2. Passing Standard for PG Courses", [
576
+ "PG students must obtain at least 50% marks in aggregate to pass a course.",
577
+ ]),
578
+ ("3. Dissertation", [
579
+ "The PG dissertation carries 12 credits and is evaluated by an internal guide and an external examiner.",
580
+ "Issued by: Office of Postgraduate Studies, Aranya Valley University (fictional).",
581
+ ]),
582
+ ],
583
+ ],
584
+ },
585
+ # ------------------------------------------------------------------ D16 (distractor)
586
+ {
587
+ "id": "D16",
588
+ "filename": "16_Hostel_and_Campus_Facilities_Guidelines_2025.pdf",
589
+ "title": "Hostel and Campus Facilities Guidelines 2025",
590
+ "doc_no": "AVU/HOSTEL/2025",
591
+ "issued": "2025-06-20",
592
+ "effective": "2025-07-01",
593
+ "version": "1.0",
594
+ "topic": "Hostel and facilities (distractor)",
595
+ "pages": [
596
+ [
597
+ ("1. Hostel Timings", [
598
+ "Hostel residents must be inside the hostel premises by 9:30 PM on all days.",
599
+ "Guests may stay in the hostel guest room for a maximum of 2 days with prior permission of the warden.",
600
+ ]),
601
+ ("2. Fees", [
602
+ "The mess fee is INR 4,500 per month, payable by the 10th of each month.",
603
+ "Late payment of hostel dues attracts a fine of INR 500.",
604
+ ]),
605
+ ("3. Allotment", [
606
+ "75% of hostel rooms are reserved for first-year students. Room allotment is valid for one academic year.",
607
+ ]),
608
+ ],
609
+ [
610
+ ("4. Campus Facilities", [
611
+ "The gymnasium is open from 6:00 AM to 9:00 AM and from 5:00 PM to 8:00 PM.",
612
+ "Campus Wi-Fi is available to residents with a daily limit of 5 GB.",
613
+ "Issued by: Chief Warden, Aranya Valley University (fictional).",
614
+ ]),
615
+ ],
616
+ ],
617
+ },
618
+ ]
scripts/generate_dataset.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Regenerates the complete SYNTHETIC dataset for EvidenceGuard AI:
3
+
4
+ 1. sample_data/*.pdf - 16 fictional university documents (real PDFs)
5
+ 2. sample_data/corpus_manifest.json - metadata for every document
6
+ 3. evaluation_data/questions.json - 100 evaluation questions with evidence pages
7
+ 4. evaluation_data/questions.csv - same, flattened
8
+
9
+ Every evidence phrase is located in the extracted PDF text; the script fails loudly if
10
+ any phrase cannot be found, so the questions are guaranteed to be derived from the PDFs.
11
+
12
+ Usage: python scripts/generate_dataset.py
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import csv
17
+ import json
18
+ import sys
19
+ from collections import Counter
20
+ from pathlib import Path
21
+
22
+ ROOT = Path(__file__).resolve().parents[1]
23
+ sys.path.insert(0, str(ROOT))
24
+ sys.path.insert(0, str(ROOT / "scripts"))
25
+
26
+ from reportlab.lib import colors # noqa: E402
27
+ from reportlab.lib.enums import TA_CENTER # noqa: E402
28
+ from reportlab.lib.pagesizes import A4 # noqa: E402
29
+ from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet # noqa: E402
30
+ from reportlab.lib.units import cm # noqa: E402
31
+ from reportlab.platypus import (PageBreak, Paragraph, SimpleDocTemplate, # noqa: E402
32
+ Spacer, Table, TableStyle)
33
+
34
+ from corpus_content import DOCUMENTS, UNIVERSITY # noqa: E402
35
+ from questions_spec import Q # noqa: E402
36
+ from src.text_utils import normalize # noqa: E402
37
+
38
+ SAMPLE = ROOT / "sample_data"
39
+ EVAL = ROOT / "evaluation_data"
40
+ BANNER = "SYNTHETIC DEMONSTRATION DATA - fictional university, not a real policy"
41
+
42
+
43
+ def _styles():
44
+ ss = getSampleStyleSheet()
45
+ return {
46
+ "title": ParagraphStyle("t", parent=ss["Title"], fontSize=16, leading=20, spaceAfter=6),
47
+ "sub": ParagraphStyle("s", parent=ss["Normal"], fontSize=9.5, alignment=TA_CENTER,
48
+ textColor=colors.HexColor("#444444")),
49
+ "h": ParagraphStyle("h", parent=ss["Heading2"], fontSize=12, spaceBefore=10, spaceAfter=4),
50
+ "p": ParagraphStyle("p", parent=ss["Normal"], fontSize=10.5, leading=14.5, spaceAfter=6),
51
+ }
52
+
53
+
54
+ def render_pdf(doc: dict, path: Path) -> None:
55
+ st = _styles()
56
+ total_pages = len(doc["pages"])
57
+
58
+ def on_page(canvas, d):
59
+ canvas.saveState()
60
+ canvas.setFillColor(colors.HexColor("#B00020"))
61
+ canvas.setFont("Helvetica-Bold", 8.5)
62
+ canvas.drawCentredString(A4[0] / 2, A4[1] - 1.1 * cm, BANNER)
63
+ canvas.setFillColor(colors.HexColor("#555555"))
64
+ canvas.setFont("Helvetica", 8.5)
65
+ canvas.drawString(2 * cm, 1.2 * cm, f"{doc['doc_no']} | {doc['title']}")
66
+ canvas.drawRightString(A4[0] - 2 * cm, 1.2 * cm, f"Page {d.page} of {total_pages}")
67
+ canvas.restoreState()
68
+
69
+ flow = [
70
+ Paragraph(UNIVERSITY + " (fictional)", st["sub"]),
71
+ Paragraph(doc["title"], st["title"]),
72
+ ]
73
+ meta = Table(
74
+ [["Document No.", doc["doc_no"], "Version", doc["version"]],
75
+ ["Issued", doc["issued"], "Effective from", doc["effective"]]],
76
+ colWidths=[3.0 * cm, 5.2 * cm, 3.0 * cm, 5.0 * cm],
77
+ )
78
+ meta.setStyle(TableStyle([
79
+ ("FONT", (0, 0), (-1, -1), "Helvetica", 9),
80
+ ("FONT", (0, 0), (0, -1), "Helvetica-Bold", 9),
81
+ ("FONT", (2, 0), (2, -1), "Helvetica-Bold", 9),
82
+ ("GRID", (0, 0), (-1, -1), 0.4, colors.grey),
83
+ ("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#F4F6F8")),
84
+ ]))
85
+ flow += [meta, Spacer(1, 8)]
86
+ for pi, page in enumerate(doc["pages"]):
87
+ if pi > 0:
88
+ flow.append(PageBreak())
89
+ for heading, paras in page:
90
+ flow.append(Paragraph(heading, st["h"]))
91
+ for para in paras:
92
+ flow.append(Paragraph(para, st["p"]))
93
+ SimpleDocTemplate(str(path), pagesize=A4, topMargin=2 * cm, bottomMargin=2 * cm,
94
+ leftMargin=2 * cm, rightMargin=2 * cm, title=doc["title"],
95
+ author="EvidenceGuard AI synthetic data generator",
96
+ subject=BANNER).build(flow, onFirstPage=on_page, onLaterPages=on_page)
97
+
98
+
99
+ def extract_pages(path: Path) -> list[str]:
100
+ import pymupdf
101
+ with pymupdf.open(str(path)) as pdf:
102
+ return [p.get_text() for p in pdf]
103
+
104
+
105
+ def main() -> None:
106
+ SAMPLE.mkdir(exist_ok=True)
107
+ EVAL.mkdir(exist_ok=True)
108
+ manifest, page_text = [], {}
109
+ for doc in DOCUMENTS:
110
+ path = SAMPLE / doc["filename"]
111
+ render_pdf(doc, path)
112
+ pages = extract_pages(path)
113
+ assert len(pages) == len(doc["pages"]), f"{doc['id']}: expected {len(doc['pages'])} pages, got {len(pages)}"
114
+ page_text[doc["id"]] = [normalize(p) for p in pages]
115
+ manifest.append({k: doc[k] for k in ("id", "filename", "title", "doc_no", "issued",
116
+ "effective", "version", "topic")} | {"pages": len(pages)})
117
+ (SAMPLE / "corpus_manifest.json").write_text(json.dumps(manifest, indent=2))
118
+ by_id = {d["id"]: d for d in DOCUMENTS}
119
+
120
+ rows = []
121
+ for q in Q:
122
+ ev = []
123
+ for doc_id, phrase in q["evidence"]:
124
+ pages = [i + 1 for i, t in enumerate(page_text[doc_id]) if normalize(phrase) in t]
125
+ if not pages:
126
+ raise SystemExit(f"[{q['id']}] evidence phrase not found in {doc_id}: {phrase!r}")
127
+ ev.append({"doc_id": doc_id, "document": by_id[doc_id]["filename"],
128
+ "title": by_id[doc_id]["title"], "page": pages[0], "phrase": phrase})
129
+ for kw in q["keywords"]: # every key fact must exist in its evidence
130
+ alts = [normalize(a).strip() for a in kw.split("|")]
131
+ if ev and not any(any(a in page_text[e["doc_id"]][e["page"] - 1] for a in alts) for e in ev):
132
+ raise SystemExit(f"[{q['id']}] keyword {kw!r} not present in its evidence pages")
133
+ rows.append({
134
+ "id": q["id"], "category": q["category"], "question": q["question"],
135
+ "expected_answer": q["expected_answer"], "answer_keywords": q["keywords"],
136
+ "evidence": ev,
137
+ "supporting_document": "; ".join(sorted({e["document"] for e in ev})) or "NONE",
138
+ "supporting_page": "; ".join(f"{e['doc_id']} p.{e['page']}" for e in ev) or "NONE",
139
+ "expected_evidence_status": q["status"], "expected_behaviour": q["behaviour"],
140
+ })
141
+
142
+ (EVAL / "questions.json").write_text(json.dumps(rows, indent=2))
143
+ with open(EVAL / "questions.csv", "w", newline="") as f:
144
+ w = csv.DictWriter(f, fieldnames=["id", "category", "question", "expected_answer", "answer_keywords",
145
+ "supporting_document", "supporting_page",
146
+ "expected_evidence_status", "expected_behaviour"])
147
+ w.writeheader()
148
+ for r in rows:
149
+ w.writerow({k: ("; ".join(r[k]) if k == "answer_keywords" else r[k]) for k in w.fieldnames})
150
+
151
+ print(f"Generated {len(manifest)} PDFs ({sum(m['pages'] for m in manifest)} pages) in {SAMPLE}")
152
+ print(f"Generated {len(rows)} questions:", dict(Counter(r["category"] for r in rows)))
153
+
154
+
155
+ if __name__ == "__main__":
156
+ main()
scripts/make_diagrams.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Draws assets/architecture.png and assets/workflow.png with matplotlib (no external tools)."""
2
+ from pathlib import Path
3
+
4
+ import matplotlib
5
+
6
+ matplotlib.use("Agg")
7
+ import matplotlib.pyplot as plt # noqa: E402
8
+ from matplotlib.patches import FancyArrowPatch, FancyBboxPatch # noqa: E402
9
+
10
+ ASSETS = Path(__file__).resolve().parents[1] / "assets"
11
+ ASSETS.mkdir(exist_ok=True)
12
+ INK, MUTED, SURF = "#0b0b0b", "#52514e", "#fcfcfb"
13
+ BLUE, ORANGE, AQUA, YELLOW = "#cde2fb", "#fbdccd", "#c9eedf", "#fbe7b5"
14
+ EDGE = {BLUE: "#2a78d6", ORANGE: "#eb6834", AQUA: "#1baf7a", YELLOW: "#c98500", "#eeeeea": "#8a8986"}
15
+
16
+
17
+ def box(ax, x, y, w, h, text, fill, size=9, bold=False):
18
+ ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.02,rounding_size=0.08",
19
+ fc=fill, ec=EDGE.get(fill, "#8a8986"), lw=1.3))
20
+ ax.text(x + w / 2, y + h / 2, text, ha="center", va="center", fontsize=size, color=INK,
21
+ fontweight="bold" if bold else "normal", wrap=True)
22
+
23
+
24
+ def arrow(ax, x1, y1, x2, y2, color=MUTED, style="-|>", ls="-"):
25
+ ax.add_patch(FancyArrowPatch((x1, y1), (x2, y2), arrowstyle=style, mutation_scale=12, color=color,
26
+ lw=1.3, linestyle=ls, shrinkA=2, shrinkB=2))
27
+
28
+
29
+ def architecture():
30
+ fig, ax = plt.subplots(figsize=(13, 7.4))
31
+ ax.set_xlim(0, 13)
32
+ ax.set_ylim(0, 7.4)
33
+ ax.axis("off")
34
+ fig.patch.set_facecolor(SURF)
35
+ ax.text(0.2, 7.05, "EvidenceGuard AI - system architecture", fontsize=14, fontweight="bold", color=INK)
36
+
37
+ # ingestion layer
38
+ ax.text(0.2, 6.45, "Ingestion layer", fontsize=10, color=MUTED, fontweight="bold")
39
+ box(ax, 0.2, 5.4, 1.9, 0.85, "PDF upload /\nsample_data", "#eeeeea")
40
+ box(ax, 2.5, 5.4, 2.1, 0.85, "Text extraction\n(PyMuPDF / pypdf)", BLUE)
41
+ box(ax, 5.0, 5.4, 2.1, 0.85, "Cleaning +\nmetadata (title, date)", BLUE)
42
+ box(ax, 7.5, 5.4, 2.1, 0.85, "Sentence-aware\nchunking (70 words)", BLUE)
43
+ box(ax, 10.0, 5.95, 2.8, 0.6, "Embeddings -> FAISS index", BLUE, 8.5)
44
+ box(ax, 10.0, 5.2, 2.8, 0.6, "BM25 keyword index", BLUE, 8.5)
45
+ for x in (2.1, 4.6, 7.1):
46
+ arrow(ax, x, 5.82, x + 0.4, 5.82)
47
+ arrow(ax, 9.6, 5.9, 10.0, 6.2)
48
+ arrow(ax, 9.6, 5.75, 10.0, 5.5)
49
+
50
+ # system A
51
+ ax.text(0.2, 4.65, "System A - Baseline RAG", fontsize=10, color=MUTED, fontweight="bold")
52
+ box(ax, 0.2, 3.75, 2.2, 0.7, "Question", "#eeeeea")
53
+ box(ax, 2.8, 3.75, 2.4, 0.7, "Dense retrieval\n(top-5, FAISS)", BLUE)
54
+ box(ax, 5.6, 3.75, 2.4, 0.7, "LLM answer\n+ citations", ORANGE)
55
+ box(ax, 8.4, 3.75, 2.0, 0.7, "Answer\n(always)", "#eeeeea")
56
+ arrow(ax, 2.4, 4.1, 2.8, 4.1)
57
+ arrow(ax, 5.2, 4.1, 5.6, 4.1)
58
+ arrow(ax, 8.0, 4.1, 8.4, 4.1)
59
+
60
+ # system B
61
+ ax.text(0.2, 3.15, "System B - EvidenceGuard RAG", fontsize=10, color=MUTED, fontweight="bold")
62
+ y = 2.05
63
+ steps = [("Hybrid retrieval\nFAISS + BM25 (RRF)", BLUE), ("Cross-encoder\nreranking", BLUE),
64
+ ("Evidence\nsufficiency", AQUA), ("Conflict search +\ncontradiction (NLI\n+ numeric rules)", AQUA),
65
+ ("Grounded LLM\ngeneration", ORANGE), ("Citation\nvalidation", AQUA), ("Confidence +\nabstention", YELLOW)]
66
+ x = 0.2
67
+ w = 1.68
68
+ for i, (t, c) in enumerate(steps):
69
+ box(ax, x, y, w, 0.95, t, c, 8.2)
70
+ if i:
71
+ arrow(ax, x - 0.14, y + 0.47, x, y + 0.47)
72
+ x += w + 0.14
73
+ box(ax, 0.2, 0.5, 3.6, 0.95, "ANSWERED / PARTIAL /\nCONFLICT WARNING / ABSTAINED", YELLOW, 8.5, True)
74
+ box(ax, 4.2, 0.5, 4.2, 0.95, "Explanation: why it answered, partially answered\nor refused (scores, thresholds, missing terms)", "#eeeeea", 8.3)
75
+ box(ax, 8.8, 0.5, 4.0, 0.95, "Gradio UI: chat, evidence panel,\nside-by-side comparison, evaluation dashboard", "#eeeeea", 8.3)
76
+ arrow(ax, x - 0.14 - w / 2, y, 2.0, 1.45)
77
+ arrow(ax, 3.8, 0.97, 4.2, 0.97)
78
+ arrow(ax, 8.4, 0.97, 8.8, 0.97)
79
+ arrow(ax, 11.4, 5.2, 11.4, 4.45, ls="--")
80
+ ax.text(11.5, 4.75, "shared indexes", fontsize=8, color=MUTED)
81
+ ax.text(0.2, 0.12, "Blue = retrieval · Green = verification (EvidenceGuard contribution) · Orange = LLM · "
82
+ "Yellow = decision. Every model has an offline fallback (LSA embeddings, lexical reranker, rule verifier, "
83
+ "extractive composer).", fontsize=8, color=MUTED)
84
+ fig.savefig(ASSETS / "architecture.png", dpi=160, bbox_inches="tight", facecolor=SURF)
85
+ plt.close(fig)
86
+
87
+
88
+ def workflow():
89
+ fig, ax = plt.subplots(figsize=(8.6, 10.5))
90
+ ax.set_xlim(0, 8.6)
91
+ ax.set_ylim(0, 10.5)
92
+ ax.axis("off")
93
+ fig.patch.set_facecolor(SURF)
94
+ ax.text(0.2, 10.15, "EvidenceGuard AI - decision workflow", fontsize=14, fontweight="bold", color=INK)
95
+ cx, w, h = 1.0, 4.0, 0.62
96
+ ys = [9.2, 8.25, 7.3, 6.35, 5.4, 4.45, 3.5, 2.55]
97
+ labels = [("User question (+ follow-up context)", "#eeeeea"),
98
+ ("Hybrid retrieval: FAISS + BM25, fused by RRF", BLUE),
99
+ ("Cross-encoder reranking -> top-5 passages", BLUE),
100
+ ("Evidence sufficiency: relevance & coverage", AQUA),
101
+ ("Conflict-search retrieval + contradiction check", AQUA),
102
+ ("Context-grounded generation (conflict-aware)", ORANGE),
103
+ ("Citation validation of every sentence", AQUA),
104
+ ("Confidence = 0.4 rel + 0.4 cov + 0.2 support", YELLOW)]
105
+ for (t, c), y in zip(labels, ys):
106
+ box(ax, cx, y, w, h, t, c, 8.8)
107
+ for a, b in zip(ys, ys[1:]):
108
+ arrow(ax, cx + w / 2, a, cx + w / 2, b + h)
109
+ # side exits
110
+ box(ax, 5.6, 6.35, 2.8, h, "ABSTAIN: insufficient\nevidence (+ missing terms)", YELLOW, 8)
111
+ arrow(ax, cx + w, 6.35 + h / 2, 5.6, 6.35 + h / 2)
112
+ ax.text(5.08, 6.88, "insufficient", fontsize=7.5, color=MUTED)
113
+ box(ax, 5.6, 4.45, 2.8, h, "Conflict note: both versions,\ndates, newer document", "#eeeeea", 8)
114
+ arrow(ax, 5.6, 4.45 + h / 2, cx + w, 4.45 + h / 2, ls="--")
115
+ box(ax, 5.6, 3.5, 2.8, h, "Drop unsupported sentences;\nnone left -> ABSTAIN", YELLOW, 8)
116
+ arrow(ax, cx + w, 3.5 + h / 2, 5.6, 3.5 + h / 2)
117
+ outs = [("ANSWERED", 0.2), ("PARTIAL", 2.2), ("CONFLICT\nWARNING", 4.2), ("ABSTAINED", 6.2)]
118
+ for t, x in outs:
119
+ box(ax, x, 1.1, 1.8, 0.75, t, YELLOW, 8.5, True)
120
+ arrow(ax, cx + w / 2, 2.55, x + 0.9, 1.85)
121
+ box(ax, 0.2, 0.15, 7.8, 0.6, "Explanation + evidence panel (passages, scores, conflicts, citation checks) shown to the user",
122
+ "#eeeeea", 8.5)
123
+ fig.savefig(ASSETS / "workflow.png", dpi=160, bbox_inches="tight", facecolor=SURF)
124
+ plt.close(fig)
125
+
126
+
127
+ if __name__ == "__main__":
128
+ architecture()
129
+ workflow()
130
+ print("diagrams written to", ASSETS)
scripts/questions_spec.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Evaluation question specification (100 questions) for the SYNTHETIC AVU corpus.
3
+
4
+ Fields
5
+ id, category, question, expected_answer,
6
+ keywords : list of key facts that a correct answer must contain (normalised match;
7
+ an item "a|b" means either a or b is acceptable),
8
+ evidence : list of (doc_id, exact phrase) - the page is located automatically,
9
+ status : expected evidence status -> sufficient | insufficient | conflicting
10
+ behaviour : expected system behaviour -> answer | abstain | flag_conflict | correct_premise
11
+
12
+ Categories: answerable (30), multi_passage (20), missing (15), misleading (15), conflicting (20)
13
+ """
14
+
15
+ Q = []
16
+
17
+
18
+ def add(qid, cat, question, answer, keywords, evidence, status, behaviour):
19
+ Q.append(dict(id=qid, category=cat, question=question, expected_answer=answer,
20
+ keywords=keywords, evidence=evidence, status=status, behaviour=behaviour))
21
+
22
+
23
+ # ----------------------------------------------------------------- answerable (30)
24
+ A = "answerable"
25
+ add("A01", A, "How many marks are allotted to internal assessment in a theory course?",
26
+ "40 marks are allotted to internal assessment (the end-semester exam carries 60).",
27
+ ["40 marks"], [("D04", "40 marks for internal assessment")], "sufficient", "answer")
28
+ add("A02", A, "How many marks does the end-semester examination of a theory course carry?",
29
+ "60 marks.", ["60 marks"], [("D04", "60 marks for the end-semester examination")], "sufficient", "answer")
30
+ add("A03", A, "What is the duration of an internal test?",
31
+ "Internal tests are 60 minutes long.", ["60 minutes"],
32
+ [("D04", "Internal tests are of 60 minutes duration")], "sufficient", "answer")
33
+ add("A04", A, "Within how many working days must a medical certificate be submitted to take a make-up test?",
34
+ "Within 3 working days of the missed test.", ["3 working days"],
35
+ [("D04", "medical certificate is submitted within 3 working days of the missed test")], "sufficient", "answer")
36
+ add("A05", A, "By what time on the due date must assignments be submitted on AVU-Learn?",
37
+ "By 11:59 PM on the due date.", ["11:59"],
38
+ [("D05", "by 11:59 PM on the due date")], "sufficient", "answer")
39
+ add("A06", A, "What is the maximum file size allowed for an assignment submission?",
40
+ "A single PDF of no more than 10 MB.", ["10 mb"],
41
+ [("D05", "single PDF file of no more than 10 MB")], "sufficient", "answer")
42
+ add("A07", A, "What is the maximum number of members allowed in a group assignment?",
43
+ "At most 4 members.", ["4 members"], [("D05", "at most 4 members")], "sufficient", "answer")
44
+ add("A08", A, "What happens if an assignment has a similarity index above 40%?",
45
+ "It receives zero marks and is referred to the Academic Integrity Committee.",
46
+ ["zero marks", "academic integrity committee"],
47
+ [("D05", "A similarity index above 40% results in zero marks")], "sufficient", "answer")
48
+ add("A09", A, "On what date do the odd semester end-semester examinations conclude?",
49
+ "12 December 2025.", ["12 december 2025"],
50
+ [("D06", "conclude on 12 December 2025")], "sufficient", "answer")
51
+ add("A10", A, "What are the timings of the afternoon examination session?",
52
+ "2:00 PM to 5:00 PM.", ["2:00 pm", "5:00 pm"],
53
+ [("D06", "Afternoon session: 2:00 PM to 5:00 PM")], "sufficient", "answer")
54
+ add("A11", A, "How early must students report before an examination session starts?",
55
+ "30 minutes before the start of the session.", ["30 minutes"],
56
+ [("D06", "Students must report 30 minutes before the start of the session")], "sufficient", "answer")
57
+ add("A12", A, "On which date is the MDS302 Generative AI and LLMs examination?",
58
+ "03 December 2025, morning session.", ["03 december 2025|3 december 2025"],
59
+ [("D06", "MDS302 Generative AI and LLMs")], "sufficient", "answer")
60
+ add("A13", A, "What type of calculator is permitted in the examination hall?",
61
+ "Only non-programmable scientific calculators.", ["non-programmable"],
62
+ [("D06", "Only non-programmable scientific calculators are permitted")], "sufficient", "answer")
63
+ add("A14", A, "By when will the odd semester examination results be announced?",
64
+ "By 15 January 2026.", ["15 january 2026"],
65
+ [("D06", "will be announced by 15 January 2026")], "sufficient", "answer")
66
+ add("A15", A, "What tuition fee waiver does a student with a CGPA of 9.0 or above receive?",
67
+ "A 50% tuition fee waiver.", ["50%"],
68
+ [("D07", "CGPA of 9.0 or above in the previous academic year receive a 50% tuition fee waiver")], "sufficient", "answer")
69
+ add("A16", A, "What tuition fee waiver is given to students with a CGPA between 8.5 and 8.99?",
70
+ "A 25% tuition fee waiver.", ["25%"],
71
+ [("D07", "between 8.5 and 8.99 receive a 25% tuition fee waiver")], "sufficient", "answer")
72
+ add("A17", A, "What is the amount of the need-based scholarship?",
73
+ "INR 30,000 per year.", ["30000"],
74
+ [("D07", "need-based scholarship of INR 30,000 per year")], "sufficient", "answer")
75
+ add("A18", A, "What CGPA is required for a scholarship to be renewed?",
76
+ "A CGPA of at least 8.0 (and no disciplinary action).", ["8.0"],
77
+ [("D07", "renewed annually subject to a CGPA of at least 8.0")], "sufficient", "answer")
78
+ add("A19", A, "Can a student hold an external scholarship together with a university scholarship?",
79
+ "Yes, a student may simultaneously hold one external (government or private) scholarship.",
80
+ ["one external"], [("D07", "simultaneously hold one external")], "sufficient", "answer")
81
+ add("A20", A, "How many credits must a PG student register for in a semester?",
82
+ "A minimum of 18 and a maximum of 26 credits.", ["18", "26"],
83
+ [("D09", "minimum of 18 and a maximum of 26 credits per semester")], "sufficient", "answer")
84
+ add("A21", A, "What is the fee for late course registration?",
85
+ "INR 2,000 (late registration allowed until 22 July 2025).", ["2000"],
86
+ [("D09", "with a late fee of INR 2,000")], "sufficient", "answer")
87
+ add("A22", A, "How many open electives can a student register for per semester?",
88
+ "A maximum of 2 open electives per semester.", ["2 open electives"],
89
+ [("D09", "maximum of 2 open electives per semester")], "sufficient", "answer")
90
+ add("A23", A, "For how many semesters can a student take academic leave during the programme?",
91
+ "A maximum of two semesters.", ["two semesters"],
92
+ [("D10", "maximum of two semesters")], "sufficient", "answer")
93
+ add("A24", A, "How far in advance must an application for academic leave be submitted?",
94
+ "At least 30 days before the start of the semester (except medical emergencies).", ["30 days"],
95
+ [("D10", "at least 30 days before the start of the semester")], "sufficient", "answer")
96
+ add("A25", A, "What fee must a student pay per semester while on academic leave?",
97
+ "A registration retention fee of INR 5,000 per semester (no tuition fee).", ["5000"],
98
+ [("D10", "registration retention fee of INR 5,000 per semester")], "sufficient", "answer")
99
+ add("A26", A, "What is the maximum duration allowed to complete a programme?",
100
+ "The normal duration plus two years, including any academic leave.", ["two years"],
101
+ [("D10", "normal duration plus two years")], "sufficient", "answer")
102
+ add("A27", A, "What are the Central Library's opening hours on Saturdays?",
103
+ "9:00 AM to 5:00 PM.", ["9:00 am", "5:00 pm"],
104
+ [("D11", "from 9:00 AM to 5:00 PM on Saturdays")], "sufficient", "answer")
105
+ add("A28", A, "How many books can research scholars borrow and for how long?",
106
+ "Up to 8 books for 30 days.", ["8 books", "30 days"],
107
+ [("D11", "Research scholars may borrow up to 8 books for 30 days")], "sufficient", "answer")
108
+ add("A29", A, "Which grade is awarded for marks between 80 and 89?",
109
+ "Grade A+ (grade point 9).", ["a+"],
110
+ [("D13", "Grade A+ (grade point 9): 80 to 89 marks")], "sufficient", "answer")
111
+ add("A30", A, "What minimum mark is needed in the end-semester examination to pass a course?",
112
+ "At least 35% in the end-semester examination (21 out of 60).", ["35%|21 out of 60"],
113
+ [("D13", "at least 35% in the end-semester examination (21 out of 60)")], "sufficient", "answer")
114
+
115
+ # ----------------------------------------------------------------- multi-passage (20)
116
+ M = "multi_passage"
117
+ add("M01", M, "What minimum internal assessment marks are needed for exam eligibility, and how many marks is each internal test worth?",
118
+ "At least 16 out of 40 IA marks (40%); each internal test is worth 15 marks.", ["16", "15 marks"],
119
+ [("D03", "that is, at least 16 out of 40"), ("D04", "Internal Test 1 (15 marks)")], "sufficient", "answer")
120
+ add("M02", M, "When is Internal Test 1 held this semester, and what must a student do to take a make-up test if they miss it through illness?",
121
+ "1-5 September 2025; submit a medical certificate within 3 working days to take one make-up test.",
122
+ ["1 september 2025", "3 working days"],
123
+ [("D14", "Internal Test 1: 1 September 2025 to 5 September 2025"),
124
+ ("D04", "medical certificate is submitted within 3 working days of the missed test")], "sufficient", "answer")
125
+ add("M03", M, "What happens to a student whose attendance is still short after condonation, and to whom can an eligibility decision be appealed?",
126
+ "They are marked NE (Not Eligible) and must re-register; appeals go to the Controller of Examinations within 3 working days.",
127
+ ["not eligible", "controller of examinations"],
128
+ [("D01", "will be marked NE"), ("D03", "may appeal against an eligibility decision")], "sufficient", "answer")
129
+ add("M04", M, "Does approved medical leave count as attendance, and for how many days can a Head of Department approve medical leave?",
130
+ "No, it does not count as attendance (only for condonation); up to 15 days per semester.",
131
+ ["15 days", "condonation"],
132
+ [("D10", "Medical leave of up to 15 days"), ("D10", "Approved medical leave does not count as attendance")], "sufficient", "answer")
133
+ add("M05", M, "Do library dues affect examination eligibility, and what is charged for a lost library book?",
134
+ "No, but they must be cleared before results are released; lost books cost twice the current price.",
135
+ ["results", "twice"],
136
+ [("D03", "Library dues do not affect examination eligibility"), ("D11", "paid for at twice the current price")], "sufficient", "answer")
137
+ add("M06", M, "What CGPA is needed for First Class with Distinction, and what CGPA earns a 50% merit tuition waiver?",
138
+ "8.0 or above for First Class with Distinction; 9.0 or above for a 50% waiver.", ["8.0", "9.0"],
139
+ [("D13", "First Class with Distinction is awarded for a CGPA of 8.0 or above"),
140
+ ("D07", "CGPA of 9.0 or above in the previous academic year receive a 50% tuition fee waiver")], "sufficient", "answer")
141
+ add("M07", M, "Can reference books be borrowed, and how many times can a borrowed book be renewed?",
142
+ "Reference books cannot be borrowed; a borrowed book can be renewed once if not reserved.", ["cannot", "once"],
143
+ [("D11", "Reference books cannot be borrowed"), ("D11", "may be renewed once")], "sufficient", "answer")
144
+ add("M08", M, "How many internal assessment marks are given for assignments, and in what file format must assignments be submitted?",
145
+ "5 marks; as a single PDF file (max 10 MB).", ["5 marks", "pdf"],
146
+ [("D04", "Assignment (5 marks)"), ("D05", "single PDF file of no more than 10 MB")], "sufficient", "answer")
147
+ add("M09", M, "When does odd semester course registration close, and what is the last date for late registration?",
148
+ "Closes 15 July 2025; late registration until 22 July 2025.", ["15 july 2025", "22 july 2025"],
149
+ [("D09", "closes on 15 July 2025"), ("D09", "permitted until 22 July 2025")], "sufficient", "answer")
150
+ add("M10", M, "When do odd semester classes begin and what is the last working day of the odd semester?",
151
+ "Classes begin 21 July 2025; last working day 21 November 2025.", ["21 july 2025", "21 november 2025"],
152
+ [("D14", "classes begin on 21 July 2025"), ("D14", "Last working day of the odd semester: 21 November 2025")], "sufficient", "answer")
153
+ add("M11", M, "What documents must be submitted for the need-based scholarship, and how recent must the income certificate be?",
154
+ "An income certificate from a competent authority issued within the last 6 months, and the previous year's marks card.",
155
+ ["6 months", "marks card"],
156
+ [("D07", "within the last 6 months and the marks card of the previous year")], "sufficient", "answer")
157
+ add("M12", M, "If a student qualifies for both the merit and need-based scholarships, what do they receive, and what is needed to renew it?",
158
+ "Only the higher-value scholarship; renewal needs a CGPA of at least 8.0 and no disciplinary action.",
159
+ ["higher-value", "8.0"],
160
+ [("D07", "the higher-value scholarship is awarded"), ("D07", "renewed annually subject to a CGPA of at least 8.0")], "sufficient", "answer")
161
+ add("M13", M, "How long is each internal test and in which weeks of the semester are they conducted?",
162
+ "60 minutes; in the 7th and 13th weeks.", ["60 minutes", "7th", "13th"],
163
+ [("D04", "conducted in the 7th and 13th weeks of the semester")], "sufficient", "answer")
164
+ add("M14", M, "Within how many days are internal assessment marks published after a test, and how long do students have to request a review?",
165
+ "Within 10 working days; review requests within 5 working days of publication.",
166
+ ["10 working days", "5 working days"],
167
+ [("D04", "within 10 working days of each test"), ("D04", "within 5 working days of publication")], "sufficient", "answer")
168
+ add("M15", M, "How long an extension can an instructor grant for an assignment, and what happens if the similarity index is above 20%?",
169
+ "Up to 5 days if requested before the deadline; similarity above 20% requires resubmission within 3 days.",
170
+ ["5 days", "resubmission"],
171
+ [("D05", "Extensions of up to 5 days"), ("D05", "A similarity index above 20% requires resubmission within 3 days")], "sufficient", "answer")
172
+ add("M16", M, "Which MSc Data Science Semester 3 examination is held in the afternoon session, and what are the afternoon session timings?",
173
+ "MDS305 Security for Data Science on 10 December 2025; 2:00 PM to 5:00 PM.",
174
+ ["security for data science|mds305", "2:00 pm"],
175
+ [("D06", "MDS305 Security for Data Science - Afternoon session"), ("D06", "Afternoon session: 2:00 PM to 5:00 PM")], "sufficient", "answer")
176
+ add("M17", M, "When are supplementary examinations held, and what is the maximum grade that can be awarded in them?",
177
+ "In June and July; the maximum grade is A.", ["june", "grade a"],
178
+ [("D13", "Supplementary examinations are held in June and July")], "sufficient", "answer")
179
+ add("M18", M, "How many backlog courses prevent promotion to the next year, and when can backlogs be cleared through supplementary examinations?",
180
+ "More than 4 backlog courses; supplementary exams are held in June and July.", ["4 backlog", "june"],
181
+ [("D13", "more than 4 backlog courses"), ("D13", "Supplementary examinations are held in June and July")], "sufficient", "answer")
182
+ add("M19", M, "How is participation in university-approved events treated for attendance, and who must approve it?",
183
+ "Counted as present for up to 10 contact hours per semester with prior approval of the Head of Department.",
184
+ ["10 contact hours", "head of department"],
185
+ [("D01", "counted as present for up to 10 contact hours")], "sufficient", "answer")
186
+ add("M20", M, "A student returning from academic leave must re-register within which window, and what are the regular odd semester registration dates?",
187
+ "Within the regular registration window: 1 July 2025 to 15 July 2025.", ["1 july 2025", "15 july 2025"],
188
+ [("D10", "must re-register within the regular registration window"),
189
+ ("D09", "opens on 1 July 2025 and closes on 15 July 2025")], "sufficient", "answer")
190
+
191
+ # ----------------------------------------------------------------- missing (15)
192
+ N = "missing"
193
+ missing = [
194
+ "What is the fee for revaluation of answer scripts?",
195
+ "Who is the current Vice-Chancellor of Aranya Valley University?",
196
+ "What is the annual hostel fee for PhD students?",
197
+ "Does the university offer a sports quota scholarship?",
198
+ "What is the dress code during end-semester examinations?",
199
+ "Can students take the end-semester examinations online from home?",
200
+ "What minimum CGPA is required to sit for campus placements?",
201
+ "How many total credits are required to graduate from the MSc Data Science programme?",
202
+ "What is the fee for a duplicate hall ticket?",
203
+ "On what date will the 2026 convocation ceremony be held?",
204
+ "What is the university policy on using generative AI tools such as ChatGPT in assignments?",
205
+ "What is the parking fee for students' two-wheelers on campus?",
206
+ "What is the late fine for paying tuition fees after the due date?",
207
+ "Does the university offer a tuition fee concession for siblings?",
208
+ "What is the timetable for the even semester examinations in May 2026?",
209
+ ]
210
+ for i, q in enumerate(missing, 1):
211
+ add(f"N{i:02d}", N, q, "The documents do not contain this information; the system should abstain.",
212
+ [], [], "insufficient", "abstain")
213
+
214
+ # ----------------------------------------------------------------- misleading / irrelevant context (15)
215
+ I = "misleading"
216
+ add("I01", I, "Given that internal assessment carries 50 marks, how many marks does the end-semester examination carry?",
217
+ "The premise is wrong: IA carries 40 marks and the end-semester examination carries 60 marks.",
218
+ ["40 marks", "60 marks"], [("D04", "40 marks for internal assessment")], "sufficient", "correct_premise")
219
+ add("I02", I, "Since PG students can register for up to 30 credits, what is the minimum number of credits?",
220
+ "The maximum is 26, not 30; the minimum is 18.", ["18", "26"],
221
+ [("D09", "minimum of 18 and a maximum of 26 credits per semester")], "sufficient", "correct_premise")
222
+ add("I03", I, "As research scholars can borrow 10 books, what is their loan period?",
223
+ "Research scholars may borrow up to 8 books (not 10) for 30 days.", ["8 books", "30 days"],
224
+ [("D11", "Research scholars may borrow up to 8 books for 30 days")], "sufficient", "correct_premise")
225
+ add("I04", I, "Since a CGPA of 8.0 earns a 50% merit tuition waiver, what does a CGPA of 9.0 earn?",
226
+ "The 50% waiver requires a CGPA of 9.0 or above; 8.5-8.99 earns 25%.", ["9.0", "50%"],
227
+ [("D07", "CGPA of 9.0 or above in the previous academic year receive a 50% tuition fee waiver")], "sufficient", "correct_premise")
228
+ add("I05", I, "Given that academic leave can be taken for up to four semesters, how early must a student apply?",
229
+ "Academic leave is limited to two semesters; apply at least 30 days before the semester.",
230
+ ["two semesters", "30 days"],
231
+ [("D10", "maximum of two semesters"), ("D10", "at least 30 days before the start of the semester")], "sufficient", "correct_premise")
232
+ add("I06", I, "As the MDS301 Deep Learning exam is in the afternoon session, what time does it start?",
233
+ "It is in the morning session (01 December 2025), which starts at 10:00 AM.", ["10:00 am"],
234
+ [("D06", "MDS301 Deep Learning - Morning session"), ("D06", "Morning session: 10:00 AM to 1:00 PM")], "sufficient", "correct_premise")
235
+ add("I07", I, "Since make-up internal tests are allowed for any reason, how many can a student take per semester?",
236
+ "Make-up tests are only for medical grounds; one make-up test per semester.", ["one make-up test", "medical"],
237
+ [("D04", "may take one make-up test per semester")], "sufficient", "correct_premise")
238
+ add("I08", I, "What is the late fee for course registration?",
239
+ "INR 2,000 (not the INR 500 hostel fine).", ["2000"],
240
+ [("D09", "with a late fee of INR 2,000")], "sufficient", "answer")
241
+ add("I09", I, "Above what similarity percentage must an assignment be resubmitted?",
242
+ "Above 20%.", ["20%"],
243
+ [("D05", "A similarity index above 20% requires resubmission within 3 days")], "sufficient", "answer")
244
+ add("I10", I, "At what time does the Central Library close on working days?",
245
+ "10:00 PM.", ["10:00 pm"],
246
+ [("D11", "from 8:00 AM to 10:00 PM on working days")], "sufficient", "answer")
247
+ add("I11", I, "How many days before the examinations is the attendance shortage list published?",
248
+ "7 days before the commencement of end-semester examinations.", ["7 days"],
249
+ [("D01", "published 7 days before the commencement of end-semester examinations")], "sufficient", "answer")
250
+ add("I12", I, "How many contact hours of approved event participation can be counted as present?",
251
+ "Up to 10 contact hours per semester.", ["10 contact hours"],
252
+ [("D01", "counted as present for up to 10 contact hours")], "sufficient", "answer")
253
+ add("I13", I, "What is the minimum CGPA for First Class (without distinction)?",
254
+ "6.5 (First Class is CGPA 6.5 to 7.99).", ["6.5"],
255
+ [("D13", "First Class is awarded for a CGPA from 6.5 to 7.99")], "sufficient", "answer")
256
+ add("I14", I, "For how many days can a course instructor extend an assignment deadline?",
257
+ "Up to 5 days.", ["5 days"], [("D05", "Extensions of up to 5 days")], "sufficient", "answer")
258
+ add("I15", I, "Is a calculator with programmable memory allowed in the examination hall?",
259
+ "No - only non-programmable scientific calculators are permitted.", ["non-programmable"],
260
+ [("D06", "Only non-programmable scientific calculators are permitted")], "sufficient", "answer")
261
+
262
+ # ----------------------------------------------------------------- conflicting (20)
263
+ C = "conflicting"
264
+ add("C01", C, "What is the minimum attendance required to appear for end-semester examinations?",
265
+ "Conflict: Attendance Regulations 2023 say 75%; Circular 2025/014 revises it to 80% from 2025-26 (supersedes).",
266
+ ["75%", "80%"], [("D01", "minimum of 75% attendance"), ("D02", "revised to 80%")], "conflicting", "flag_conflict")
267
+ add("C02", C, "Up to what percentage can an attendance shortage be condoned on medical grounds?",
268
+ "Conflict: 10% under the 2023 regulations; limited to 5% by the 2025 circular.",
269
+ ["10%", "5%"], [("D01", "shortage of attendance of up to 10%"), ("D02", "limited to 5%")], "conflicting", "flag_conflict")
270
+ add("C03", C, "What is the condonation fee per course for attendance shortage?",
271
+ "Conflict: INR 500 (2023 regulations) vs INR 1,000 (2025 circular).",
272
+ ["500", "1000"], [("D01", "condonation fee of INR 500 per course"), ("D02", "revised to INR 1,000 per course")], "conflicting", "flag_conflict")
273
+ add("C04", C, "According to the examination eligibility rules, what attendance is needed in a course to sit its end-semester exam?",
274
+ "Conflict: the eligibility rules (2024) state 75%, but the 2025 circular raises the requirement to 80%.",
275
+ ["75%", "80%"], [("D03", "attendance requirement of 75%"), ("D02", "revised to 80%")], "conflicting", "flag_conflict")
276
+ add("C05", C, "What is the last date to apply for a scholarship for 2025-26?",
277
+ "Conflict: 31 August 2025 (policy) vs extended to 15 September 2025 (notice).",
278
+ ["31 august 2025", "15 september 2025"],
279
+ [("D07", "by 31 August 2025"), ("D08", "extended to 15 September 2025")], "conflicting", "flag_conflict")
280
+ add("C06", C, "What is the family income limit for the need-based scholarship?",
281
+ "Conflict: INR 6,00,000 (policy) vs INR 8,00,000 (revised notice).",
282
+ ["600000", "800000"],
283
+ [("D07", "does not exceed INR 6,00,000"), ("D08", "revised to INR 8,00,000")], "conflicting", "flag_conflict")
284
+ add("C07", C, "Are late assignment submissions accepted?",
285
+ "Conflict: the Assignment Policy accepts up to 3 days late with 10%/day penalty; the IA Guidelines say late assignments will not be accepted for IA.",
286
+ ["10%", "not be accepted"],
287
+ [("D05", "Late submissions are accepted for up to 3 calendar days"), ("D04", "will not be accepted for internal assessment")], "conflicting", "flag_conflict")
288
+ add("C08", C, "What is the penalty for submitting an assignment one day late?",
289
+ "Conflict: 10% of maximum marks per day (Assignment Policy) vs not accepted at all (IA Guidelines).",
290
+ ["10%", "not be accepted"],
291
+ [("D05", "penalty of 10% of the maximum marks per day"), ("D04", "will not be accepted for internal assessment")], "conflicting", "flag_conflict")
292
+ add("C09", C, "How many books can a postgraduate student borrow from the library?",
293
+ "Conflict: 5 books (2023 regulations) vs 6 books from 1 August 2025 (notice).",
294
+ ["5 books", "6 books"],
295
+ [("D11", "Postgraduate students may borrow up to 5 books"), ("D12", "may borrow up to 6 books")], "conflicting", "flag_conflict")
296
+ add("C10", C, "For how many days can a postgraduate student keep a borrowed library book?",
297
+ "Conflict: 14 days (2023) vs 21 days (2025 notice).", ["14 days", "21 days"],
298
+ [("D11", "Postgraduate students may borrow up to 5 books for 14 days"), ("D12", "for a period of 21 days")], "conflicting", "flag_conflict")
299
+ add("C11", C, "What is the library overdue fine per book per day?",
300
+ "Conflict: INR 5 (2023) vs INR 10 (2025 notice).", ["inr 5 ", "inr 10 "],
301
+ [("D11", "overdue fine of INR 5 per book per day"), ("D12", "revised to INR 10 per book per day")], "conflicting", "flag_conflict")
302
+ add("C12", C, "How long is the add/drop period for elective courses?",
303
+ "Conflict: 10 working days (Registration Guidelines) vs 7 working days (Academic Calendar).",
304
+ ["10 working days", "7 working days"],
305
+ [("D09", "within 10 working days from the start of classes"), ("D14", "7 working days from the start of classes")], "conflicting", "flag_conflict")
306
+ add("C13", C, "What minimum aggregate percentage is needed to pass a postgraduate course?",
307
+ "Conflict: 40% (Grading Policy) vs 50% for PG courses (PG Handbook).", ["40%", "50%"],
308
+ [("D13", "at least 40% marks in aggregate"), ("D15", "at least 50% marks in aggregate")], "conflicting", "flag_conflict")
309
+ add("C14", C, "On what date do the odd semester end-semester examinations begin?",
310
+ "Conflict: 1 December 2025 (Timetable, Oct 2025) vs 3 December 2025 (Academic Calendar, June 2025).",
311
+ ["1 december 2025", "3 december 2025"],
312
+ [("D06", "commence on 1 December 2025"), ("D14", "End-semester examinations: from 3 December 2025")], "conflicting", "flag_conflict")
313
+ add("C15", C, "Can I drop an elective course 9 working days after classes start?",
314
+ "Conflict: allowed under the Registration Guidelines (10 working days) but not under the Academic Calendar (7 working days).",
315
+ ["10 working days", "7 working days"],
316
+ [("D09", "within 10 working days from the start of classes"), ("D14", "7 working days from the start of classes")], "conflicting", "flag_conflict")
317
+ add("C16", C, "If my attendance in a course is 78%, am I eligible for the end-semester examination?",
318
+ "Conflict: eligible under the 2023 rule (75%), but below the 80% minimum under the 2025 circular (condonable between 75% and 80%).",
319
+ ["75%", "80%"], [("D01", "minimum of 75% attendance"), ("D02", "revised to 80%")], "conflicting", "flag_conflict")
320
+ add("C17", C, "If a PG student scores 45% in aggregate in a course, do they pass?",
321
+ "Conflict: pass under the Grading Policy (40%), fail under the PG Handbook (50%).", ["40%", "50%"],
322
+ [("D13", "at least 40% marks in aggregate"), ("D15", "at least 50% marks in aggregate")], "conflicting", "flag_conflict")
323
+ add("C18", C, "What is the lowest attendance percentage that can be condoned on medical grounds?",
324
+ "Conflict: 65% under the 2023 regulations vs 75% under the 2025 circular.", ["65%", "75%"],
325
+ [("D01", "attendance between 65% and 75%"), ("D02", "attendance between 75% and 80%")], "conflicting", "flag_conflict")
326
+ add("C19", C, "Which attendance rule is the latest, and what minimum attendance does it require?",
327
+ "Conflict: the 2025 circular (latest) requires 80%, superseding the 75% of the 2023 regulations.",
328
+ ["80%", "75%"], [("D02", "revised to 80%"), ("D01", "minimum of 75% attendance")], "conflicting", "flag_conflict")
329
+ add("C20", C, "According to the academic calendar, what is the scholarship application deadline, and has it changed?",
330
+ "Conflict: the calendar says 31 August 2025, but the notice extends it to 15 September 2025.",
331
+ ["31 august 2025", "15 september 2025"],
332
+ [("D14", "Last date for scholarship applications: 31 August 2025"), ("D08", "extended to 15 September 2025")], "conflicting", "flag_conflict")
333
+
334
+ assert len(Q) == 100, len(Q)
scripts/render_report_docx.js ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Renders reports/report_model.json (built by build_report.py) into a Word document with docx-js.
2
+ // Usage: node scripts/render_report_docx.js reports/report_model.json reports/project_report.docx
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const {
6
+ Document, Packer, Paragraph, TextRun, HeadingLevel, AlignmentType, Table, TableRow, TableCell,
7
+ WidthType, ShadingType, ImageRun, PageBreak, LevelFormat, Footer, Header, PageNumber,
8
+ TableOfContents, BorderStyle,
9
+ } = require("docx");
10
+
11
+ const [, , inPath, outPath] = process.argv;
12
+ const blocks = JSON.parse(fs.readFileSync(inPath, "utf8"));
13
+ const FONT = "Calibri";
14
+ const CM = 567; // DXA per cm
15
+ const CONTENT_W = 16 * CM; // A4 21 cm - 2 x 2.5 cm margins
16
+
17
+ function pngSize(file) {
18
+ const b = fs.readFileSync(file);
19
+ return { w: b.readUInt32BE(16), h: b.readUInt32BE(20), data: b };
20
+ }
21
+
22
+ const children = [];
23
+ const numberRefs = [];
24
+ const h1Titles = blocks.filter(x => x.t === "h1").map(x => x.text);
25
+ for (const b of blocks) {
26
+ switch (b.t) {
27
+ case "title":
28
+ children.push(new Paragraph({ spacing: { before: 2400, after: 240 }, alignment: AlignmentType.CENTER,
29
+ children: [new TextRun({ text: b.title, font: FONT, size: 56, bold: true, color: "1C5CAB" })] }));
30
+ children.push(new Paragraph({ spacing: { after: 960 }, alignment: AlignmentType.CENTER,
31
+ children: [new TextRun({ text: b.subtitle, font: FONT, size: 30 })] }));
32
+ for (const l of b.lines) children.push(new Paragraph({ alignment: AlignmentType.CENTER, spacing: { after: 160 },
33
+ children: [new TextRun({ text: l, font: FONT, size: 24 })] }));
34
+ children.push(new Paragraph({ alignment: AlignmentType.CENTER, spacing: { before: 1200 },
35
+ children: [new TextRun({ text: "All documents and data in this project are SYNTHETIC DEMONSTRATION DATA describing a fictional university.",
36
+ font: FONT, size: 20, italics: true, color: "B00020" })] }));
37
+ children.push(new Paragraph({ children: [new PageBreak()] }));
38
+ children.push(new Paragraph({ spacing: { after: 240 }, children: [new TextRun({ text: "Contents", font: FONT, size: 32, bold: true, color: "1C5CAB" })] }));
39
+ for (const t of h1Titles) children.push(new Paragraph({ spacing: { after: 90 }, indent: { left: t.match(/^\d/) ? 0 : 0 },
40
+ children: [new TextRun({ text: t, font: FONT, size: 23 })] }));
41
+ break;
42
+ case "h1":
43
+ children.push(new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun(b.text)] })); break;
44
+ case "h2":
45
+ children.push(new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun(b.text)] })); break;
46
+ case "p":
47
+ children.push(new Paragraph({ alignment: AlignmentType.JUSTIFIED, spacing: { after: 140, line: 300 },
48
+ children: [new TextRun({ text: b.text, font: FONT, size: 22 })] })); break;
49
+ case "caption":
50
+ children.push(new Paragraph({ alignment: AlignmentType.CENTER, spacing: { before: 60, after: 220 },
51
+ children: [new TextRun({ text: b.text, font: FONT, size: 18, italics: true, color: "52514E" })] })); break;
52
+ case "bullets":
53
+ case "numbers": {
54
+ const ref = b.t === "bullets" ? "bul" : `num${numberRefs.length}`;
55
+ if (b.t === "numbers") numberRefs.push(ref);
56
+ for (const it of b.items) children.push(new Paragraph({ numbering: { reference: ref, level: 0 },
57
+ spacing: { after: 80, line: 290 }, children: [new TextRun({ text: it, font: FONT, size: 22 })] }));
58
+ break;
59
+ }
60
+ case "refs":
61
+ b.items.forEach((r, i) => children.push(new Paragraph({ spacing: { after: 100 }, indent: { left: 567, hanging: 567 },
62
+ children: [new TextRun({ text: `[${i + 1}]\t${r}`, font: FONT, size: 20 })] })));
63
+ break;
64
+ case "code":
65
+ for (const line of b.text.split("\n")) children.push(new Paragraph({ spacing: { after: 0 },
66
+ shading: { fill: "F4F6F8", type: ShadingType.CLEAR, color: "auto" },
67
+ children: [new TextRun({ text: line, font: "Consolas", size: 18 })] }));
68
+ break;
69
+ case "pagebreak":
70
+ children.push(new Paragraph({ children: [new PageBreak()] })); break;
71
+ case "img": {
72
+ if (!fs.existsSync(b.path)) break;
73
+ const s = pngSize(b.path);
74
+ const wPx = Math.round(b.width_cm * 37.8);
75
+ let hPx = Math.round(wPx * s.h / s.w);
76
+ const maxH = 22 * 37.8;
77
+ let w = wPx;
78
+ if (hPx > maxH) { w = Math.round(wPx * maxH / hPx); hPx = Math.round(maxH); }
79
+ children.push(new Paragraph({ alignment: AlignmentType.CENTER, spacing: { before: 120 },
80
+ children: [new ImageRun({ type: "png", data: s.data, transformation: { width: w, height: hPx },
81
+ altText: { title: path.basename(b.path), description: b.caption || path.basename(b.path), name: path.basename(b.path) } })] }));
82
+ break;
83
+ }
84
+ case "table": {
85
+ const n = b.header.length;
86
+ let widths = b.widths || Array(n).fill(16 / n);
87
+ const tot = widths.reduce((a, c) => a + c, 0);
88
+ const dx = widths.map(x => Math.floor(x / tot * CONTENT_W));
89
+ dx[dx.length - 1] += CONTENT_W - dx.reduce((a, c) => a + c, 0);
90
+ const sz = Math.round((b.size || 8) * 2);
91
+ const border = { style: BorderStyle.SINGLE, size: 4, color: "BFBFBF" };
92
+ const borders = { top: border, bottom: border, left: border, right: border };
93
+ const mkCell = (text, i, head) => new TableCell({
94
+ width: { size: dx[i], type: WidthType.DXA }, borders,
95
+ shading: head ? { fill: "DCE8F7", type: ShadingType.CLEAR, color: "auto" } : undefined,
96
+ margins: { top: 40, bottom: 40, left: 70, right: 70 },
97
+ children: [new Paragraph({ children: [new TextRun({ text: String(text), font: FONT, size: sz, bold: head })] })],
98
+ });
99
+ const rows = [new TableRow({ tableHeader: true, children: b.header.map((h, i) => mkCell(h, i, true)) })];
100
+ for (const r of b.rows) rows.push(new TableRow({ cantSplit: true, children: r.map((c, i) => mkCell(c, i, false)) }));
101
+ children.push(new Table({ width: { size: CONTENT_W, type: WidthType.DXA }, columnWidths: dx, rows }));
102
+ break;
103
+ }
104
+ }
105
+ }
106
+
107
+ const numberingConfig = [{ reference: "bul", levels: [{ level: 0, format: LevelFormat.BULLET, text: "•",
108
+ alignment: AlignmentType.LEFT, style: { paragraph: { indent: { left: 567, hanging: 283 } } } }] }];
109
+ for (const ref of numberRefs) numberingConfig.push({ reference: ref, levels: [{ level: 0, format: LevelFormat.DECIMAL,
110
+ text: "%1.", alignment: AlignmentType.LEFT, style: { paragraph: { indent: { left: 567, hanging: 340 } } } }] });
111
+
112
+ const doc = new Document({
113
+ creator: "EvidenceGuard AI report builder",
114
+ title: "EvidenceGuard AI - MSc Project Report",
115
+ features: { updateFields: true },
116
+ styles: {
117
+ default: { document: { run: { font: FONT, size: 22 } } },
118
+ paragraphStyles: [
119
+ { id: "Heading1", name: "Heading 1", basedOn: "Normal", next: "Normal", quickFormat: true,
120
+ run: { font: FONT, size: 32, bold: true, color: "1C5CAB" },
121
+ paragraph: { spacing: { before: 360, after: 160 }, keepNext: true, outlineLevel: 0 } },
122
+ { id: "Heading2", name: "Heading 2", basedOn: "Normal", next: "Normal", quickFormat: true,
123
+ run: { font: FONT, size: 26, bold: true, color: "0B0B0B" },
124
+ paragraph: { spacing: { before: 240, after: 120 }, keepNext: true, outlineLevel: 1 } },
125
+ ],
126
+ },
127
+ numbering: { config: numberingConfig },
128
+ sections: [{
129
+ properties: { page: { size: { width: 11906, height: 16838 },
130
+ margin: { top: 1418, bottom: 1418, left: 1418, right: 1418 } } },
131
+ headers: { default: new Header({ children: [new Paragraph({ alignment: AlignmentType.RIGHT,
132
+ children: [new TextRun({ text: "EvidenceGuard AI - MSc Project Report (synthetic data)", font: FONT, size: 16, color: "8A8986" })] })] }) },
133
+ footers: { default: new Footer({ children: [new Paragraph({ alignment: AlignmentType.CENTER,
134
+ children: [new TextRun({ children: ["Page ", PageNumber.CURRENT, " of ", PageNumber.TOTAL_PAGES], font: FONT, size: 18 })] })] }) },
135
+ children,
136
+ }],
137
+ });
138
+
139
+ Packer.toBuffer(doc).then(buf => { fs.writeFileSync(outPath, buf); console.log("docx written", outPath); });
scripts/run_evaluation.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Runs the complete experimental evaluation of EvidenceGuard AI.
3
+
4
+ Steps
5
+ 1. Stratified DEV/TEST split of the 100 questions (30% per category, rounded: 29 dev / 71 test, seed 42).
6
+ 2. Threshold calibration of the verifier on the DEV split only (grid search, objective =
7
+ behaviour accuracy of the complete system). Saved to results/calibrated_thresholds.json.
8
+ 3. Runs the 4 configurations on all 100 questions:
9
+ 1. Baseline RAG 2. RAG + hybrid retrieval & reranking
10
+ 3. RAG + evidence verification 4. EvidenceGuard (complete)
11
+ 4. Writes metrics (all / test / dev), per-question results, category breakdown,
12
+ error analysis and failure cases to results/, and charts to results/charts/.
13
+
14
+ Usage:
15
+ python scripts/run_evaluation.py # auto backend
16
+ python scripts/run_evaluation.py --backend lite # fully offline components
17
+ python scripts/run_evaluation.py --backend full --llm hf_api # HF models + HF Inference API
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import csv
23
+ import itertools
24
+ import json
25
+ import platform
26
+ import random
27
+ import sys
28
+ import time
29
+ from collections import Counter, defaultdict
30
+ from pathlib import Path
31
+
32
+ ROOT = Path(__file__).resolve().parents[1]
33
+ sys.path.insert(0, str(ROOT))
34
+
35
+ import config # noqa: E402
36
+ from src.evaluation import aggregate, by_category, classify_error, score_question # noqa: E402
37
+ from src.text_utils import normalize # noqa: E402
38
+
39
+ RES = config.RESULTS_DIR
40
+ CH = config.CHARTS_DIR
41
+ ORDER = ["baseline", "rerank", "verify", "full"]
42
+ SHORT = {"baseline": "Baseline RAG", "rerank": "+ Reranking", "verify": "+ Verification", "full": "EvidenceGuard"}
43
+ COLORS = {"baseline": "#2a78d6", "rerank": "#eb6834", "verify": "#1baf7a", "full": "#eda100"} # validated palette
44
+
45
+
46
+ def split(questions, dev_frac=0.3, seed=42):
47
+ rng = random.Random(seed)
48
+ by = defaultdict(list)
49
+ for q in questions:
50
+ by[q["category"]].append(q["id"])
51
+ dev = set()
52
+ for cat, ids in sorted(by.items()):
53
+ ids = sorted(ids)
54
+ rng.shuffle(ids)
55
+ dev |= set(ids[: round(len(ids) * dev_frac)])
56
+ return dev
57
+
58
+
59
+ def relevance_fn_factory(kb, questions):
60
+ from sklearn.feature_extraction.text import TfidfVectorizer
61
+ from sklearn.metrics.pairwise import cosine_similarity
62
+ vec = TfidfVectorizer(stop_words="english", sublinear_tf=True).fit(
63
+ [c.text for c in kb.chunks] + [q["question"] for q in questions])
64
+
65
+ def f(q, a):
66
+ return float(cosine_similarity(vec.transform([q]), vec.transform([a]))[0, 0])
67
+ return f
68
+
69
+
70
+ def calibrate(system, dev_qs, page_text):
71
+ """Grid search on DEV only. Two stages: sufficiency/abstention, then conflict sensitivity."""
72
+ base = dict(system.verifier.th)
73
+ pipe = system.pipelines["full"]
74
+
75
+ def score(th):
76
+ system.set_thresholds(th)
77
+ rows = [score_question(q, pipe.answer(q["question"]), page_text) for q in dev_qs]
78
+ a = aggregate(rows)
79
+ return a["behaviour_accuracy"], a["abstention_accuracy"], a["unsupported_answer_rate"]
80
+
81
+ best, best_s = dict(base), (-1, -1, 9)
82
+ grid1 = itertools.product([0.15, 0.2, 0.25, 0.3, 0.35], [0.4, 0.45, 0.5, 0.55, 0.6, 0.65], [0.3, 0.35, 0.4])
83
+ for rel, cov, conf in grid1:
84
+ th = dict(base, min_relevance=rel, min_coverage=cov, partial_coverage=max(0.0, cov - 0.1),
85
+ min_confidence=conf)
86
+ s = score(th)
87
+ if (s[0], s[1], -s[2]) > (best_s[0], best_s[1], -best_s[2]):
88
+ best, best_s = th, s
89
+ for sc, sim in itertools.product([0.25, 0.3, 0.35, 0.45], [0.25, 0.3, 0.4]):
90
+ th = dict(best, conflict_sentence_coverage=sc, conflict_topic_sim=sim)
91
+ s = score(th)
92
+ if (s[0], s[1], -s[2]) > (best_s[0], best_s[1], -best_s[2]):
93
+ best, best_s = th, s
94
+ system.set_thresholds(best)
95
+ return best, {"dev_behaviour_accuracy": best_s[0], "dev_abstention_accuracy": best_s[1],
96
+ "dev_unsupported_rate": best_s[2]}
97
+
98
+
99
+ # ------------------------------------------------------------------------------------ charts
100
+ def charts(metrics_all, cat_tables, rows_by_cfg):
101
+ import matplotlib
102
+ matplotlib.use("Agg")
103
+ import matplotlib.pyplot as plt
104
+
105
+ plt.rcParams.update({"font.size": 10, "axes.spines.top": False, "axes.spines.right": False,
106
+ "axes.edgecolor": "#8a8986", "axes.labelcolor": "#0b0b0b", "xtick.color": "#52514e",
107
+ "ytick.color": "#52514e", "figure.facecolor": "#fcfcfb", "axes.facecolor": "#fcfcfb",
108
+ "grid.color": "#e6e5e1"})
109
+
110
+ def grouped(metric_keys, labels, title, fname, ylim=1.0, pct=True):
111
+ fig, ax = plt.subplots(figsize=(9, 4.2))
112
+ n = len(ORDER)
113
+ width = 0.8 / n
114
+ for i, cfg in enumerate(ORDER):
115
+ vals = [metrics_all[cfg][k] if metrics_all[cfg][k] is not None else 0 for k in metric_keys]
116
+ xs = [j + (i - (n - 1) / 2) * width for j in range(len(metric_keys))]
117
+ bars = ax.bar(xs, vals, width * 0.92, color=COLORS[cfg], label=SHORT[cfg], zorder=3)
118
+ for b, v in zip(bars, vals):
119
+ ax.text(b.get_x() + b.get_width() / 2, b.get_height() + ylim * 0.012,
120
+ f"{v:.2f}" if pct else f"{v:.3f}", ha="center", va="bottom", fontsize=7.5, color="#52514e")
121
+ ax.set_xticks(range(len(metric_keys)), labels)
122
+ ax.set_ylim(0, ylim * 1.12)
123
+ ax.grid(axis="y", zorder=0)
124
+ ax.set_title(title, loc="left", fontsize=12, color="#0b0b0b")
125
+ ax.legend(frameon=False, ncol=4, loc="upper left", bbox_to_anchor=(0, -0.12))
126
+ fig.tight_layout()
127
+ fig.savefig(CH / fname, dpi=150)
128
+ plt.close(fig)
129
+
130
+ grouped(["precision_at_k", "recall_at_k", "mrr", "context_precision", "context_recall"],
131
+ ["Precision@5", "Recall@5", "MRR", "Context precision", "Context recall"],
132
+ "Retrieval quality (all 100 questions)", "retrieval_comparison.png")
133
+ grouped(["answer_correctness", "behaviour_accuracy", "faithfulness", "grounded_faithfulness", "answer_relevance"],
134
+ ["Answer correctness", "Behaviour accuracy", "Faithfulness\n(to context)",
135
+ "Evidence-grounded\nfaithfulness", "Answer relevance\n(lexical proxy)"],
136
+ "Answer quality (all 100 questions)", "answer_quality_comparison.png")
137
+ grouped(["unsupported_answer_rate", "abstention_accuracy", "abstention_f1", "contradiction_f1",
138
+ "citation_support_accuracy"],
139
+ ["Unsupported answer\nrate (lower = better)", "Abstention\naccuracy", "Abstention F1",
140
+ "Contradiction\ndetection F1", "Citation support\naccuracy"],
141
+ "Reliability (all 100 questions)", "reliability_comparison.png")
142
+ tmax = max(metrics_all[c]["avg_response_time_s"] for c in ORDER)
143
+ grouped(["avg_response_time_s", "avg_retrieval_time_s", "avg_verification_time_s", "avg_generation_time_s"],
144
+ ["Total", "Retrieval + rerank", "Verification", "Generation"],
145
+ "Average time per question (seconds)", "response_time.png", ylim=tmax, pct=False)
146
+
147
+ # behaviour accuracy by category
148
+ cats = ["answerable", "multi_passage", "misleading", "conflicting", "missing"]
149
+ fig, ax = plt.subplots(figsize=(9, 4.2))
150
+ width = 0.2
151
+ for i, cfg in enumerate(ORDER):
152
+ vals = [cat_tables[cfg][c]["behaviour_accuracy"] for c in cats]
153
+ xs = [j + (i - 1.5) * width for j in range(len(cats))]
154
+ bars = ax.bar(xs, vals, width * 0.92, color=COLORS[cfg], label=SHORT[cfg], zorder=3)
155
+ for b, v in zip(bars, vals):
156
+ ax.text(b.get_x() + b.get_width() / 2, b.get_height() + 0.012, f"{v:.2f}", ha="center",
157
+ va="bottom", fontsize=7.5, color="#52514e")
158
+ ax.set_xticks(range(len(cats)), ["Answerable\n(30)", "Multi-passage\n(20)", "Misleading\n(15)",
159
+ "Conflicting\n(20)", "Missing info\n(15)"])
160
+ ax.set_ylim(0, 1.12)
161
+ ax.grid(axis="y", zorder=0)
162
+ ax.set_title("Expected-behaviour accuracy by question category", loc="left", fontsize=12)
163
+ ax.legend(frameon=False, ncol=4, loc="upper left", bbox_to_anchor=(0, -0.14))
164
+ fig.tight_layout()
165
+ fig.savefig(CH / "category_breakdown.png", dpi=150)
166
+ plt.close(fig)
167
+
168
+ # error taxonomy for baseline vs full
169
+ fig, axes = plt.subplots(1, 2, figsize=(10, 3.8), sharex=True)
170
+ kinds = ["answered unanswerable question (hallucination risk)", "missed conflict", "over-abstention (answer was available)",
171
+ "incomplete answer (some key facts missing)", "wrong/irrelevant answer content",
172
+ "retrieval failure (no gold page retrieved)"]
173
+ short = ["Answered unanswerable", "Missed conflict", "Over-abstention", "Incomplete answer",
174
+ "Wrong content", "Retrieval failure"]
175
+ mx = 0
176
+ counts = {}
177
+ for cfg in ("baseline", "full"):
178
+ c = Counter(classify_error(r) for r in rows_by_cfg[cfg])
179
+ counts[cfg] = [c.get(k, 0) for k in kinds]
180
+ mx = max(mx, max(counts[cfg]))
181
+ for ax, cfg in zip(axes, ("baseline", "full")):
182
+ bars = ax.barh(short[::-1], counts[cfg][::-1], color=COLORS[cfg], zorder=3, height=0.6)
183
+ for b, v in zip(bars, counts[cfg][::-1]):
184
+ ax.text(v + mx * 0.02, b.get_y() + b.get_height() / 2, str(v), va="center", fontsize=8, color="#52514e")
185
+ ax.set_title(f"{SHORT[cfg]} - errors ({sum(counts[cfg])})", loc="left", fontsize=11)
186
+ ax.grid(axis="x", zorder=0)
187
+ ax.set_xlim(0, mx * 1.2 + 1)
188
+ fig.tight_layout()
189
+ fig.savefig(CH / "error_analysis.png", dpi=150)
190
+ plt.close(fig)
191
+
192
+
193
+ # ------------------------------------------------------------------------------------ main
194
+ def main():
195
+ ap = argparse.ArgumentParser()
196
+ ap.add_argument("--backend", default=config.EG_BACKEND, choices=["auto", "full", "lite"])
197
+ ap.add_argument("--llm", default=config.LLM_BACKEND, choices=["auto", "hf_api", "local", "extractive"])
198
+ ap.add_argument("--no-calibrate", action="store_true")
199
+ args = ap.parse_args()
200
+
201
+ from src.system import EvidenceGuardSystem
202
+ questions = json.loads(config.EVAL_DATA_PATH.read_text())
203
+ import os
204
+ os.environ["EG_IGNORE_CALIBRATION"] = "1" # start from defaults; calibrate fresh
205
+ t0 = time.time()
206
+ system = EvidenceGuardSystem(args.backend, args.llm, thresholds=dict(config.THRESHOLDS))
207
+ print("Components:", json.dumps(system.component_names(), indent=1))
208
+ page_text = {(d, i + 1): normalize(t) for d, info in system.kb.docs.items() for i, t in enumerate(info.page_texts)}
209
+ rel_fn = relevance_fn_factory(system.kb, questions)
210
+
211
+ dev_ids = split(questions)
212
+ dev_qs = [q for q in questions if q["id"] in dev_ids]
213
+ if not args.no_calibrate:
214
+ th, dev_scores = calibrate(system, dev_qs, page_text)
215
+ (RES / "calibrated_thresholds.json").write_text(json.dumps(
216
+ {"backend": system.effective_backend, "thresholds": th, "dev_ids": sorted(dev_ids), **dev_scores}, indent=2))
217
+ print("Calibrated on DEV:", dev_scores)
218
+
219
+ rows_by_cfg, per_q = {}, []
220
+ for cfg in ORDER:
221
+ rows = []
222
+ for q in questions:
223
+ r = system.pipelines[cfg].answer(q["question"])
224
+ row = score_question(q, r, page_text, rel_fn)
225
+ row["config"] = cfg
226
+ row["split"] = "dev" if q["id"] in dev_ids else "test"
227
+ row["error_type"] = classify_error(row)
228
+ rows.append(row)
229
+ rows_by_cfg[cfg] = rows
230
+ per_q += rows
231
+ print(f"{cfg:9s} done")
232
+
233
+ metrics = {"all": {}, "test": {}, "dev": {}}
234
+ cats = {}
235
+ for cfg in ORDER:
236
+ rows = rows_by_cfg[cfg]
237
+ metrics["all"][cfg] = aggregate(rows)
238
+ metrics["test"][cfg] = aggregate([r for r in rows if r["split"] == "test"])
239
+ metrics["dev"][cfg] = aggregate([r for r in rows if r["split"] == "dev"])
240
+ cats[cfg] = by_category(rows)
241
+
242
+ meta = {
243
+ "note": "Experiments use SYNTHETIC documents of a fictional university. Results do not establish "
244
+ "real-world university policy accuracy.",
245
+ "components": system.component_names(),
246
+ "backend": args.backend, "llm_backend": args.llm,
247
+ "thresholds": system.verifier.th, "n_questions": len(questions),
248
+ "dev_questions": len(dev_ids), "test_questions": len(questions) - len(dev_ids),
249
+ "python": platform.python_version(), "machine": platform.machine(),
250
+ "cpu_count": os.cpu_count(), "runtime_s": round(time.time() - t0, 1),
251
+ "date": time.strftime("%Y-%m-%d %H:%M"),
252
+ }
253
+ (RES / "metrics.json").write_text(json.dumps(
254
+ {"meta": meta, "metrics": metrics, "by_category": cats, "config_names": SHORT}, indent=2))
255
+
256
+ keys = list(metrics["all"]["full"].keys())
257
+ with open(RES / "metrics.csv", "w", newline="") as f:
258
+ w = csv.writer(f)
259
+ w.writerow(["split", "configuration"] + keys)
260
+ for sp in ("all", "test", "dev"):
261
+ for cfg in ORDER:
262
+ w.writerow([sp, SHORT[cfg]] + [metrics[sp][cfg][k] for k in keys])
263
+ with open(RES / "category_breakdown.csv", "w", newline="") as f:
264
+ w = csv.writer(f)
265
+ w.writerow(["configuration", "category", "n", "answer_correctness", "behaviour_accuracy",
266
+ "unsupported_rate", "abstention_rate"])
267
+ for cfg in ORDER:
268
+ for c, v in cats[cfg].items():
269
+ w.writerow([SHORT[cfg], c, v["n"], v["answer_correctness"], v["behaviour_accuracy"],
270
+ v["unsupported_rate"], v["abstention_rate"]])
271
+ fields = ["config", "split", "id", "category", "question", "expected_behaviour", "decision", "abstained",
272
+ "conflict_flagged", "correct", "behaviour_ok", "unsupported", "error_type", "keywords_hit",
273
+ "keywords_total", "precision_at_k", "recall_at_k", "mrr", "faithfulness", "grounded_faithfulness",
274
+ "citation_support", "confidence", "t_total", "answer", "expected_answer", "explanation", "retrieved"]
275
+ with open(RES / "per_question_results.csv", "w", newline="") as f:
276
+ w = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore")
277
+ w.writeheader()
278
+ w.writerows(per_q)
279
+
280
+ # error analysis + failure cases
281
+ err = {cfg: Counter(r["error_type"] for r in rows_by_cfg[cfg]) for cfg in ORDER}
282
+ with open(RES / "error_analysis.csv", "w", newline="") as f:
283
+ w = csv.writer(f)
284
+ types = sorted({t for c in err.values() for t in c})
285
+ w.writerow(["error_type"] + [SHORT[c] for c in ORDER])
286
+ for t in types:
287
+ w.writerow([t] + [err[c].get(t, 0) for c in ORDER])
288
+ fails = []
289
+ for r in rows_by_cfg["full"]:
290
+ if not r["behaviour_ok"]:
291
+ b = next(x for x in rows_by_cfg["baseline"] if x["id"] == r["id"])
292
+ fails.append({k: r[k] for k in ("id", "category", "question", "expected_behaviour", "error_type",
293
+ "decision", "answer", "expected_answer", "explanation", "retrieved")}
294
+ | {"baseline_answer": b["answer"], "baseline_ok": b["behaviour_ok"]})
295
+ wins = [{"id": r["id"], "category": r["category"], "question": r["question"],
296
+ "baseline_answer": b["answer"], "evidenceguard_answer": r["answer"], "explanation": r["explanation"]}
297
+ for r, b in zip(rows_by_cfg["full"], rows_by_cfg["baseline"]) if r["behaviour_ok"] and not b["behaviour_ok"]]
298
+ (RES / "failure_cases.json").write_text(json.dumps({"evidenceguard_failures": fails,
299
+ "evidenceguard_fixes_over_baseline": wins}, indent=2))
300
+ charts(metrics["all"], cats, rows_by_cfg)
301
+
302
+ print("\n=== ALL 100 questions ===")
303
+ show = ["recall_at_k", "mrr", "answer_correctness", "behaviour_accuracy", "grounded_faithfulness",
304
+ "unsupported_answer_rate", "abstention_accuracy", "contradiction_f1", "citation_support_accuracy",
305
+ "avg_response_time_s"]
306
+ print(f"{'config':16s}" + "".join(f"{k[:14]:>15s}" for k in show))
307
+ for sp in ("all", "test"):
308
+ print(f"--- {sp}")
309
+ for cfg in ORDER:
310
+ print(f"{SHORT[cfg]:16s}" + "".join(f"{(metrics[sp][cfg][k] if metrics[sp][cfg][k] is not None else float('nan')):15.3f}" for k in show))
311
+ print("\nErrors:", {SHORT[c]: dict(err[c]) for c in ("baseline", "full")})
312
+ print(f"Runtime {meta['runtime_s']} s")
313
+
314
+
315
+ if __name__ == "__main__":
316
+ main()
scripts/significance.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Paired significance tests between configurations (exact McNemar + bootstrap 95% CI).
2
+
3
+ Reads results/per_question_results.csv and writes results/significance.json.
4
+ """
5
+ import csv
6
+ import json
7
+ import random
8
+ from math import comb
9
+ from pathlib import Path
10
+
11
+ RES = Path(__file__).resolve().parents[1] / "results"
12
+
13
+
14
+ def mcnemar_exact(b, c):
15
+ n = b + c
16
+ if n == 0:
17
+ return 1.0
18
+ k = min(b, c)
19
+ p = sum(comb(n, i) for i in range(k + 1)) / 2 ** n * 2
20
+ return min(1.0, p)
21
+
22
+
23
+ def main():
24
+ rows = list(csv.DictReader(open(RES / "per_question_results.csv")))
25
+ by = {}
26
+ for r in rows:
27
+ by.setdefault(r["config"], {})[r["id"]] = r
28
+ out = {}
29
+ for metric, field, better_low in (("behaviour_accuracy", "behaviour_ok", False),
30
+ ("unsupported_answer", "unsupported", True)):
31
+ for split in ("all", "test"):
32
+ for other in ("rerank", "verify", "full"):
33
+ ids = [i for i in by["baseline"] if split == "all" or by["baseline"][i]["split"] == "test"]
34
+ a = [by["baseline"][i][field] == "True" for i in ids]
35
+ b = [by[other][i][field] == "True" for i in ids]
36
+ n01 = sum((not x) and y for x, y in zip(a, b)) # baseline 0, other 1
37
+ n10 = sum(x and (not y) for x, y in zip(a, b))
38
+ rng = random.Random(0)
39
+ diffs = []
40
+ for _ in range(5000):
41
+ s = [rng.randrange(len(ids)) for _ in ids]
42
+ diffs.append(sum(b[j] for j in s) / len(s) - sum(a[j] for j in s) / len(s))
43
+ diffs.sort()
44
+ out[f"{metric}|{split}|baseline_vs_{other}"] = {
45
+ "n": len(ids), "baseline": round(sum(a) / len(a), 4), other: round(sum(b) / len(b), 4),
46
+ "difference": round(sum(b) / len(b) - sum(a) / len(a), 4),
47
+ "ci95": [round(diffs[125], 4), round(diffs[4874], 4)],
48
+ "only_other_true": n01, "only_baseline_true": n10,
49
+ "mcnemar_exact_p": round(mcnemar_exact(n01, n10), 6),
50
+ }
51
+ (RES / "significance.json").write_text(json.dumps(out, indent=2))
52
+ for k, v in out.items():
53
+ print(k, v)
54
+
55
+
56
+ if __name__ == "__main__":
57
+ main()
src/__init__.py ADDED
File without changes
src/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (132 Bytes). View file
 
src/__pycache__/baseline_rag.cpython-312.pyc ADDED
Binary file (5.19 kB). View file
 
src/__pycache__/document_processor.cpython-312.pyc ADDED
Binary file (11.1 kB). View file
 
src/__pycache__/embeddings.cpython-312.pyc ADDED
Binary file (4.52 kB). View file
 
src/__pycache__/enhanced_rag.cpython-312.pyc ADDED
Binary file (14.1 kB). View file
 
src/__pycache__/evidence_verifier.cpython-312.pyc ADDED
Binary file (31.6 kB). View file
 
src/__pycache__/llm_generator.cpython-312.pyc ADDED
Binary file (18.5 kB). View file
 
src/__pycache__/reranker.cpython-312.pyc ADDED
Binary file (5.99 kB). View file
 
src/__pycache__/research.cpython-312.pyc ADDED
Binary file (13.8 kB). View file
 
src/__pycache__/retrieval.cpython-312.pyc ADDED
Binary file (5.56 kB). View file
 
src/__pycache__/system.cpython-312.pyc ADDED
Binary file (4.25 kB). View file
 
src/__pycache__/text_utils.cpython-312.pyc ADDED
Binary file (9.99 kB). View file
 
src/__pycache__/vector_store.cpython-312.pyc ADDED
Binary file (7.95 kB). View file
 
src/baseline_rag.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SYSTEM A - Baseline RAG: dense retrieval (FAISS) -> LLM answer with source citations. No checks."""
2
+ from __future__ import annotations
3
+
4
+ import time
5
+
6
+ import config
7
+ from src.retrieval import DenseRetriever, HybridRetriever
8
+ from src.reranker import rerank
9
+
10
+
11
+ def passage_dicts(items):
12
+ out = []
13
+ for i, r in enumerate(items, 1):
14
+ c = r.chunk
15
+ out.append({"n": i, "doc_id": c.doc_id, "doc_name": c.doc_name, "title": c.title, "page": c.page,
16
+ "issued": c.issued, "text": c.text, "dense": round(r.dense, 4), "sparse": round(r.sparse, 4),
17
+ "rerank": None if r.rerank is None else round(r.rerank, 4), "source": r.source,
18
+ "relevance": round(r.relevance, 4)})
19
+ return out
20
+
21
+
22
+ def render_claims(claims) -> str:
23
+ return " ".join(f"{s} [{', '.join(map(str, c))}]" if c else s for s, c in claims)
24
+
25
+
26
+ class BaselineRAG:
27
+ """Standard RAG. Optionally with hybrid retrieval + reranking (ablation 'RAG + reranking')."""
28
+
29
+ def __init__(self, kb, generator, reranker=None, use_hybrid=False, use_rerank=False,
30
+ top_k: int = config.TOP_K, name: str = "Baseline RAG"):
31
+ self.kb, self.gen, self.reranker = kb, generator, reranker
32
+ self.use_rerank = use_rerank and reranker is not None
33
+ self.retriever = HybridRetriever(kb) if use_hybrid else DenseRetriever(kb)
34
+ self.top_k, self.name = top_k, name
35
+
36
+ def answer(self, question: str) -> dict:
37
+ t0 = time.perf_counter()
38
+ n = config.CANDIDATES if self.use_rerank else self.top_k
39
+ items = self.retriever.retrieve(question, n)
40
+ t_ret = time.perf_counter() - t0
41
+ t1 = time.perf_counter()
42
+ if self.use_rerank:
43
+ items = rerank(self.reranker, question, items, self.top_k)
44
+ t_rr = time.perf_counter() - t1
45
+ gen = self.gen.generate(question, items, mode="baseline")
46
+ text = render_claims(gen.claims) if gen.claims else (gen.text or "No answer generated.")
47
+ cited = sorted({c for _, cs in gen.claims for c in cs if 1 <= c <= len(items)})
48
+ return {
49
+ "system": self.name, "question": question, "answer": text,
50
+ "decision": "answered", "claims": gen.claims,
51
+ "citations": [{"n": c, "doc_name": items[c - 1].chunk.doc_name, "title": items[c - 1].chunk.title,
52
+ "page": items[c - 1].chunk.page} for c in cited],
53
+ "passages": passage_dicts(items), "sufficiency": None, "conflicts": [], "citation_checks": [],
54
+ "confidence": None,
55
+ "explanation": "Baseline RAG always answers from the top retrieved passages; it performs no "
56
+ "sufficiency, contradiction or citation checks.",
57
+ "timings": {"retrieval": t_ret, "rerank": t_rr, "verification": 0.0, "generation": gen.seconds,
58
+ "total": time.perf_counter() - t0},
59
+ "generator": gen.backend,
60
+ }
src/document_processor.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PDF ingestion: text extraction, cleaning, metadata detection and sentence-aware chunking."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import re
6
+ from dataclasses import asdict, dataclass, field
7
+ from pathlib import Path
8
+
9
+ import config
10
+ from src.text_utils import split_sentences
11
+
12
+ _BANNER = re.compile(r"SYNTHETIC DEMONSTRATION DATA.*?policy", re.I)
13
+ _FOOTER = re.compile(r"^[A-Z]{2,}/[A-Z0-9/.-]+\s*\|.*$|^Page \d+ of \d+$", re.I)
14
+ _DATE_ISO = re.compile(r"\b(20\d{2})-(\d{2})-(\d{2})\b")
15
+ _DATE_LONG = re.compile(r"\b(\d{1,2})\s+(January|February|March|April|May|June|July|August|September|"
16
+ r"October|November|December)\s+(20\d{2})\b", re.I)
17
+ _MONTHS = {m: i for i, m in enumerate(["january", "february", "march", "april", "may", "june", "july",
18
+ "august", "september", "october", "november", "december"], 1)}
19
+
20
+
21
+ @dataclass
22
+ class Chunk:
23
+ chunk_id: str
24
+ doc_id: str
25
+ doc_name: str
26
+ title: str
27
+ page: int
28
+ text: str
29
+ issued: str = "" # ISO date if known; used to decide which version is newer
30
+
31
+ def to_dict(self):
32
+ return asdict(self)
33
+
34
+
35
+ @dataclass
36
+ class DocumentInfo:
37
+ doc_id: str
38
+ doc_name: str
39
+ title: str
40
+ pages: int
41
+ chunks: int
42
+ issued: str = ""
43
+ status: str = "ok"
44
+ message: str = ""
45
+ page_texts: list = field(default_factory=list, repr=False)
46
+
47
+
48
+ def extract_pages(path: str | Path) -> list[str]:
49
+ """Return raw text of every page. PyMuPDF first, pypdf as a fallback."""
50
+ return extract_pdf(path)[0]
51
+
52
+
53
+ def extract_pdf(path: str | Path) -> tuple[list[str], str]:
54
+ """(page texts, metadata title)."""
55
+ try:
56
+ import pymupdf
57
+ with pymupdf.open(str(path)) as pdf:
58
+ return [p.get_text() for p in pdf], (pdf.metadata or {}).get("title", "") or ""
59
+ except Exception:
60
+ from pypdf import PdfReader
61
+ r = PdfReader(str(path))
62
+ title = (r.metadata.title if r.metadata and r.metadata.title else "") or ""
63
+ return [(p.extract_text() or "") for p in r.pages], title
64
+
65
+
66
+ def clean_page(text: str) -> str:
67
+ text = _BANNER.sub(" ", text or "")
68
+ lines = []
69
+ for ln in text.splitlines():
70
+ s = ln.strip()
71
+ if not s or _FOOTER.match(s):
72
+ continue
73
+ words = re.sub(r"^\d+\.\s*", "", s).split()
74
+ # Short Title-Case lines without punctuation are headings ("2. Late Submission"):
75
+ # terminate them so they become their own sentence instead of gluing onto the next one.
76
+ if (words and len(words) <= 7 and s[-1] not in ".:;,)" and words[0][0].isupper()
77
+ and all(w[0].isupper() or not w[0].isalpha() for w in words if w.lower() not in
78
+ {"and", "of", "the", "for", "to", "in", "on", "a", "-"})):
79
+ s += "."
80
+ lines.append(s)
81
+ text = "\n".join(lines)
82
+ text = re.sub(r"(\w)-\n(\w)", r"\1\2", text) # de-hyphenate line breaks
83
+ text = re.sub(r"\s*\n\s*", " ", text)
84
+ return re.sub(r"\s{2,}", " ", text).strip()
85
+
86
+
87
+ def _to_iso(text: str) -> str:
88
+ m = re.search(r"Issued\s+(20\d{2}-\d{2}-\d{2})", text)
89
+ if m:
90
+ return m.group(1)
91
+ m = _DATE_ISO.search(text)
92
+ if m:
93
+ return m.group(0)
94
+ m = _DATE_LONG.search(text)
95
+ if m:
96
+ d, mon, y = m.groups()
97
+ return f"{y}-{_MONTHS[mon.lower()]:02d}-{int(d):02d}"
98
+ return ""
99
+
100
+
101
+ def _manifest() -> dict:
102
+ p = config.SAMPLE_DATA_DIR / "corpus_manifest.json"
103
+ if p.exists():
104
+ return {m["filename"]: m for m in json.loads(p.read_text())}
105
+ return {}
106
+
107
+
108
+ def chunk_page(sentences: list[str], target_words: int, overlap: int) -> list[str]:
109
+ chunks, cur, words = [], [], 0
110
+ for s in sentences:
111
+ n = len(s.split())
112
+ if cur and words + n > target_words:
113
+ chunks.append(" ".join(cur))
114
+ cur = cur[-overlap:] if overlap else []
115
+ words = sum(len(x.split()) for x in cur)
116
+ cur.append(s)
117
+ words += n
118
+ if cur:
119
+ tail = " ".join(cur)
120
+ if not chunks or tail not in chunks[-1]:
121
+ chunks.append(tail)
122
+ return chunks
123
+
124
+
125
+ def process_pdf(path: str | Path, doc_id: str | None = None,
126
+ target_words: int | None = None, overlap: int | None = None) -> tuple[DocumentInfo, list[Chunk]]:
127
+ path = Path(path)
128
+ target_words = target_words or config.CHUNK_TARGET_WORDS
129
+ overlap = config.CHUNK_OVERLAP_SENTENCES if overlap is None else overlap
130
+ doc_id = doc_id or re.sub(r"[^A-Za-z0-9]+", "_", path.stem)[:40]
131
+ try:
132
+ raw, meta_title = extract_pdf(path)
133
+ except Exception as e: # corrupt / encrypted PDF
134
+ return DocumentInfo(doc_id, path.name, path.stem, 0, 0, status="error", message=str(e)), []
135
+
136
+ pages = [clean_page(p) for p in raw]
137
+ meta = _manifest().get(path.name, {})
138
+ first_line = next((ln.strip() for ln in (raw[0] if raw else "").splitlines()
139
+ if ln.strip() and not _BANNER.search(ln)), "")
140
+ title = meta.get("title") or (meta_title.strip() if meta_title.strip().strip("()").lower() not in ("", "untitled", "anonymous") else "") \
141
+ or first_line[:90] or path.stem
142
+ title = re.sub(r"^Aranya Valley University \(AVU\) \(fictional\)\s*", "", title).strip() or path.stem
143
+ issued = meta.get("issued") or _to_iso(" ".join(raw[:1]))
144
+
145
+ chunks: list[Chunk] = []
146
+ for pno, text in enumerate(pages, 1):
147
+ sents = split_sentences(text)
148
+ for ci, ctext in enumerate(chunk_page(sents, target_words, overlap)):
149
+ chunks.append(Chunk(f"{doc_id}-p{pno}-c{ci}", doc_id, path.name, title, pno, ctext, issued))
150
+
151
+ status, msg = "ok", "extracted"
152
+ if not any(p.strip() for p in pages):
153
+ status, msg = "warning", "no extractable text (scanned PDF? OCR is not supported)"
154
+ return DocumentInfo(doc_id, path.name, title, len(pages), len(chunks), issued, status, msg, pages), chunks
src/embeddings.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dense text embeddings.
2
+
3
+ * SentenceTransformerEmbedder - sentence-transformers/all-MiniLM-L6-v2 (384-d, Apache-2.0).
4
+ * LSAEmbedder - offline fallback: TF-IDF (word 1-2 grams) + TruncatedSVD,
5
+ L2-normalised. Must be fitted on the corpus; refitted when
6
+ documents are added.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+
12
+ import numpy as np
13
+
14
+ import config
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+
19
+ class SentenceTransformerEmbedder:
20
+ needs_fit = False
21
+
22
+ def __init__(self, model_name: str = config.EMBEDDING_MODEL):
23
+ from sentence_transformers import SentenceTransformer
24
+ self.model = SentenceTransformer(model_name, device="cpu")
25
+ self.name = f"SentenceTransformer ({model_name})"
26
+
27
+ def fit(self, texts): # no-op, kept for a uniform interface
28
+ return self
29
+
30
+ def encode(self, texts: list[str]) -> np.ndarray:
31
+ v = self.model.encode(list(texts), batch_size=32, normalize_embeddings=True,
32
+ show_progress_bar=False, convert_to_numpy=True)
33
+ return v.astype("float32")
34
+
35
+
36
+ class LSAEmbedder:
37
+ needs_fit = True
38
+
39
+ def __init__(self, dim: int = config.LSA_DIM):
40
+ self.dim = dim
41
+ self.name = "LSA (TF-IDF + TruncatedSVD) - offline fallback"
42
+ self.vec = None
43
+ self.svd = None
44
+
45
+ def fit(self, texts: list[str]):
46
+ from sklearn.decomposition import TruncatedSVD
47
+ from sklearn.feature_extraction.text import TfidfVectorizer
48
+ self.vec = TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True, min_df=1,
49
+ token_pattern=r"(?u)\b[\w.%+:-]+\b", stop_words="english")
50
+ X = self.vec.fit_transform(texts)
51
+ k = max(2, min(self.dim, X.shape[0] - 1, X.shape[1] - 1))
52
+ self.svd = TruncatedSVD(n_components=k, random_state=42).fit(X)
53
+ return self
54
+
55
+ def encode(self, texts: list[str]) -> np.ndarray:
56
+ if self.vec is None:
57
+ raise RuntimeError("LSAEmbedder must be fitted before encoding")
58
+ v = self.svd.transform(self.vec.transform(texts))
59
+ v /= np.linalg.norm(v, axis=1, keepdims=True) + 1e-12
60
+ return v.astype("float32")
61
+
62
+
63
+ def load_embedder(backend: str = config.EG_BACKEND):
64
+ if backend in ("full", "auto"):
65
+ try:
66
+ return SentenceTransformerEmbedder()
67
+ except Exception as e:
68
+ if backend == "full":
69
+ raise
70
+ log.warning("Sentence Transformer unavailable (%s); using LSA fallback", e)
71
+ return LSAEmbedder()
src/enhanced_rag.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SYSTEM B - EvidenceGuard RAG.
2
+
3
+ hybrid retrieval -> cross-encoder reranking -> evidence sufficiency -> contradiction detection
4
+ -> context-grounded generation -> citation validation -> confidence-based abstention -> explanation
5
+ Each stage can be switched off for the ablation study.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ import time
11
+ from dataclasses import asdict
12
+
13
+ import config
14
+ from src.baseline_rag import passage_dicts
15
+ from src.retrieval import DenseRetriever, HybridRetriever
16
+ from src.reranker import rerank
17
+ from src.text_utils import split_sentences
18
+
19
+ ABSTAIN_TEXT = ("I could not find sufficient evidence in the uploaded documents to answer this question. "
20
+ "Please check with the relevant university office.")
21
+ _PRESUPPOSITION = re.compile(r"^\s*(since|given that|as|because|assuming)\b", re.I)
22
+
23
+
24
+ class EvidenceGuardRAG:
25
+ def __init__(self, kb, generator, reranker, verifier, use_hybrid=True, use_rerank=True,
26
+ use_verification=True, top_k: int = config.TOP_K, name: str = "EvidenceGuard RAG"):
27
+ self.kb, self.gen, self.reranker, self.verifier = kb, generator, reranker, verifier
28
+ self.retriever = HybridRetriever(kb) if use_hybrid else DenseRetriever(kb)
29
+ self.use_rerank, self.use_verification = use_rerank, use_verification
30
+ self.top_k, self.name = top_k, name
31
+
32
+ # ------------------------------------------------------------------
33
+ def answer(self, question: str) -> dict:
34
+ T = {}
35
+ t0 = time.perf_counter()
36
+ n = config.CANDIDATES if self.use_rerank else self.top_k
37
+ items = self.retriever.retrieve(question, n)
38
+ T["retrieval"] = time.perf_counter() - t0
39
+
40
+ t = time.perf_counter()
41
+ if self.use_rerank:
42
+ items = rerank(self.reranker, question, items, self.top_k)
43
+ elif self.use_verification and items:
44
+ # Verification needs calibrated relevance scores. Score passages for gating only;
45
+ # retrieval order and the passage set stay exactly as the dense retriever returned them.
46
+ for r, s in zip(items, self.reranker.score(question, [f"{r.chunk.title}. {r.chunk.text}" for r in items])):
47
+ r.rerank = float(s)
48
+ T["rerank"] = time.perf_counter() - t
49
+
50
+ if not self.use_verification:
51
+ gen = self.gen.generate(question, items, mode="grounded")
52
+ T["verification"], T["generation"] = 0.0, gen.seconds
53
+ T["total"] = time.perf_counter() - t0
54
+ return self._package(question, items, gen.claims, "answered", None, [], [], None,
55
+ "Verification disabled for this configuration.", T, gen.backend, [])
56
+
57
+ # ---------------- 1. sufficiency
58
+ t = time.perf_counter()
59
+ ordered = sorted(items, key=lambda r: -r.relevance)
60
+ suff = self.verifier.sufficiency(question, ordered)
61
+ if suff.status == "insufficient":
62
+ T["verification"] = time.perf_counter() - t
63
+ T["generation"] = 0.0
64
+ T["total"] = time.perf_counter() - t0
65
+ why = (f"Abstained: evidence is insufficient (best passage relevance {suff.max_relevance:.2f}, "
66
+ f"query coverage {suff.coverage:.2f}; thresholds {self.verifier.th['min_relevance']:.2f} / "
67
+ f"{self.verifier.th['min_coverage']:.2f}).")
68
+ if suff.missing_terms:
69
+ why += f" Question terms not found in the retrieved passages: {', '.join(suff.missing_terms[:8])}."
70
+ return self._package(question, items, [], "abstained", suff, [], [], 0.0, why, T, "", [])
71
+
72
+ # ---------------- 2. conflict-search retrieval + contradiction detection + premise check
73
+ items = items + self.verifier.expand_for_conflicts(question, items, self.retriever)
74
+ conflicts = self.verifier.detect_conflicts(question, items)
75
+ premise = []
76
+ if _PRESUPPOSITION.search(question):
77
+ ev = [s for r in ordered[:3] for s in split_sentences(r.chunk.text)]
78
+ premise = self.verifier.premise_issues(question, ev)
79
+ T["verification"] = time.perf_counter() - t
80
+
81
+ # ---------------- 3. grounded generation
82
+ gen = self.gen.generate(question, items, mode="grounded", conflicts=conflicts, premise_notes=premise)
83
+ T["generation"] = gen.seconds
84
+ if gen.declined:
85
+ T["total"] = time.perf_counter() - t0
86
+ return self._package(question, items, [], "abstained", suff, conflicts, [], 0.0,
87
+ "Abstained: the language model reported that the passages do not contain the answer.",
88
+ T, gen.backend, premise)
89
+
90
+ # ---------------- 4. citation validation
91
+ t = time.perf_counter()
92
+ checks = self.verifier.validate_citations(gen.claims, items)
93
+ T["verification"] += time.perf_counter() - t
94
+ supported = [(c.sentence, c.cited or [self._best_cite(c)]) for c in checks if c.supported]
95
+ ratio = len(supported) / max(1, len(checks))
96
+
97
+ # ---------------- 5. confidence & decision
98
+ conf = 0.4 * min(1.0, suff.max_relevance) + 0.4 * min(1.0, suff.coverage) + 0.2 * ratio
99
+ if not supported:
100
+ decision, why = "abstained", "Abstained: none of the generated sentences could be verified against the cited passages."
101
+ elif conf < self.verifier.th["min_confidence"]:
102
+ decision, why = "abstained", f"Abstained: confidence {conf:.2f} is below the threshold {self.verifier.th['min_confidence']:.2f}."
103
+ elif conflicts:
104
+ decision = "conflict"
105
+ why = ("Answered with a conflict warning: " + "; ".join(
106
+ f"'{c.title_a}' and '{c.title_b}' disagree ({c.detail})" for c in conflicts) + ".")
107
+ elif suff.status == "partial" or ratio < 1:
108
+ decision = "partial"
109
+ why = f"Partially answered: query coverage {suff.coverage:.2f}"
110
+ if suff.missing_terms:
111
+ why += f"; not covered: {', '.join(suff.missing_terms[:6])}"
112
+ if ratio < 1:
113
+ why += f"; {len(checks) - len(supported)} unsupported sentence(s) removed"
114
+ why += "."
115
+ else:
116
+ decision = "answered"
117
+ why = (f"Answered: relevance {suff.max_relevance:.2f}, coverage {suff.coverage:.2f}, "
118
+ f"{len(supported)}/{len(checks)} sentences verified against their citations.")
119
+ T["total"] = time.perf_counter() - t0
120
+ return self._package(question, items, supported if decision != "abstained" else [], decision, suff,
121
+ conflicts, checks, conf, why, T, gen.backend, premise)
122
+
123
+ @staticmethod
124
+ def _best_cite(check):
125
+ m = re.search(r"\[(\d+)\]", check.sentence)
126
+ return int(m.group(1)) if m else 1
127
+
128
+ # ------------------------------------------------------------------
129
+ def _render(self, claims, decision, conflicts, items, premise):
130
+ if decision == "abstained":
131
+ return ABSTAIN_TEXT
132
+ parts = []
133
+ if conflicts:
134
+ parts.append("⚠️ **Conflicting evidence found.** The documents disagree:")
135
+ shown = set()
136
+ for c in conflicts[:2]:
137
+ for title, issued, sent, n in ((c.title_a, c.issued_a, c.sentence_a, c.passage_a),
138
+ (c.title_b, c.issued_b, c.sentence_b, c.passage_b)):
139
+ if sent in shown:
140
+ continue
141
+ shown.add(sent)
142
+ parts.append(f"- *{title}* (issued {issued or 'unknown'}): {sent} [{n}]")
143
+ newest = conflicts[0].newer
144
+ if newest:
145
+ parts.append(f"The more recent document is *{newest}*"
146
+ + (", which explicitly revises the earlier rule." if conflicts[0].explicit_update else ".")
147
+ + " Please confirm with the issuing office before relying on either version.")
148
+ extra = [(s, c) for s, c in claims if s not in shown]
149
+ if extra:
150
+ parts.append("**Most relevant evidence:** " + " ".join(f"{s} [{', '.join(map(str, c))}]" for s, c in extra))
151
+ return "\n".join(parts)
152
+ for p in premise:
153
+ parts.append(f"**Note:** {p[0].upper() + p[1:]}.")
154
+ parts.append(" ".join(f"{s} [{', '.join(map(str, c))}]" for s, c in claims))
155
+ return "\n\n".join(parts)
156
+
157
+ def _package(self, question, items, claims, decision, suff, conflicts, checks, conf, why, T, backend, premise):
158
+ cited = sorted({c for _, cs in claims for c in cs if 1 <= c <= len(items)})
159
+ if decision == "conflict":
160
+ cited = sorted(set(cited) | {n for cf in conflicts for n in (cf.passage_a, cf.passage_b)})
161
+ return {
162
+ "system": self.name, "question": question,
163
+ "answer": self._render(claims, decision, conflicts, items, premise),
164
+ "decision": decision, "claims": claims,
165
+ "citations": [{"n": c, "doc_name": items[c - 1].chunk.doc_name, "title": items[c - 1].chunk.title,
166
+ "page": items[c - 1].chunk.page} for c in cited],
167
+ "passages": passage_dicts(items),
168
+ "sufficiency": asdict(suff) if suff else None,
169
+ "conflicts": [asdict(c) for c in conflicts],
170
+ "citation_checks": [asdict(c) for c in checks],
171
+ "premise_notes": premise,
172
+ "confidence": None if conf is None else round(conf, 3),
173
+ "explanation": why, "timings": T, "generator": backend,
174
+ }
src/evaluation.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluation metrics for EvidenceGuard AI (all computed from the generated question set).
2
+
3
+ Retrieval Precision@K, Recall@K, MRR (gold unit = document + page)
4
+ Answer quality Answer correctness (key-fact match / correct abstention),
5
+ Faithfulness (claims supported by the retrieved context),
6
+ Evidence-grounded faithfulness (claims that come from the gold evidence pages),
7
+ Answer relevance (TF-IDF cosine question vs answer - lexical proxy),
8
+ Context precision (rank-weighted AP@K), Context recall (key facts present in context)
9
+ Reliability Unsupported answer rate, Abstention accuracy/P/R/F1,
10
+ Contradiction detection P/R/F1, Citation support accuracy, Behaviour accuracy
11
+ Efficiency mean total / retrieval / generation / verification time (seconds)
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ import statistics as st
17
+
18
+ from src.text_utils import fact_values, keyword_present, normalize, split_sentences
19
+
20
+ _ABSTAIN_PAT = re.compile(r"(could not find sufficient evidence|insufficient_evidence|do(es)? not (contain|mention|"
21
+ r"provide|specify)|not (mentioned|specified|available) in|no information)", re.I)
22
+
23
+
24
+ def is_abstention(result: dict) -> bool:
25
+ return result["decision"] == "abstained" or bool(_ABSTAIN_PAT.search(result["answer"] or ""))
26
+
27
+
28
+ def _gold_units(q):
29
+ return {(e["doc_id"], e["page"]) for e in q["evidence"]}
30
+
31
+
32
+ def _support(sentence: str, text: str) -> bool:
33
+ """Loose support check used only for evaluation: values present + >=70% token overlap."""
34
+ s_vals, t_vals = fact_values(sentence), fact_values(text)
35
+ if s_vals - t_vals:
36
+ return False
37
+ st_ = set(re.findall(r"[a-z0-9]+", normalize(sentence)))
38
+ tt = set(re.findall(r"[a-z0-9]+", normalize(text)))
39
+ return len(st_ & tt) / max(1, len(st_)) >= 0.7
40
+
41
+
42
+ def score_question(q: dict, r: dict, page_text: dict, relevance_fn=None) -> dict:
43
+ gold = _gold_units(q)
44
+ ctx = r["passages"]
45
+ units = [(p["doc_id"], p["page"]) for p in ctx]
46
+ k = max(1, len(units))
47
+ rel_flags = [u in gold for u in units]
48
+ has_gold = bool(gold)
49
+ abst = is_abstention(r)
50
+ exp_abst = q["expected_behaviour"] == "abstain"
51
+ answer = r["answer"] or ""
52
+ kws = q["answer_keywords"]
53
+ kw_hits = [keyword_present(answer, kw) for kw in kws]
54
+ ctx_text = " ".join(p["text"] for p in ctx)
55
+
56
+ # ---------------- correctness
57
+ if exp_abst:
58
+ correct = abst
59
+ else:
60
+ correct = (not abst) and all(kw_hits)
61
+ flagged = r["decision"] == "conflict" or bool(r.get("conflicts"))
62
+ if q["expected_behaviour"] == "flag_conflict":
63
+ behaviour_ok = (not abst) and flagged and all(kw_hits)
64
+ elif exp_abst:
65
+ behaviour_ok = abst
66
+ else:
67
+ behaviour_ok = (not abst) and all(kw_hits)
68
+
69
+ # ---------------- faithfulness of answer claims
70
+ claims = [s for s, _ in r.get("claims", [])] if r.get("claims") else split_sentences(answer)
71
+ claims = [c for c in claims if len(c.split()) >= 3]
72
+ if not abst and claims:
73
+ faith = sum(_support(c, ctx_text) for c in claims) / len(claims)
74
+ gold_text = " ".join(page_text[u] for u in gold)
75
+ gfaith = (sum(_support(c, gold_text) for c in claims) / len(claims)) if gold else 0.0
76
+ else:
77
+ faith = gfaith = None
78
+
79
+ # ---------------- citations
80
+ cited = r.get("citations", [])
81
+ if not abst and cited:
82
+ cite_acc = sum((c_doc_id(c, ctx), c["page"]) in gold for c in cited) / len(cited)
83
+ else:
84
+ cite_acc = None
85
+
86
+ # ---------------- context precision (AP@K) and recall (key facts in context)
87
+ if has_gold:
88
+ hits, ap = 0, 0.0
89
+ for i, f in enumerate(rel_flags, 1):
90
+ if f:
91
+ hits += 1
92
+ ap += hits / i
93
+ ctx_precision = ap / max(1, hits) if hits else 0.0
94
+ ctx_recall = (sum(keyword_present(ctx_text, kw) for kw in kws) / len(kws)) if kws else None
95
+ p_at_k = sum(rel_flags) / k
96
+ r_at_k = len(gold & set(units)) / len(gold)
97
+ rr = next((1 / i for i, f in enumerate(rel_flags, 1) if f), 0.0)
98
+ else:
99
+ ctx_precision = ctx_recall = p_at_k = r_at_k = rr = None
100
+
101
+ return {
102
+ "id": q["id"], "category": q["category"], "question": q["question"],
103
+ "expected_behaviour": q["expected_behaviour"], "expected_status": q["expected_evidence_status"],
104
+ "decision": r["decision"], "abstained": abst, "conflict_flagged": flagged,
105
+ "answer": answer, "expected_answer": q["expected_answer"],
106
+ "keywords_hit": sum(kw_hits), "keywords_total": len(kws),
107
+ "correct": correct, "behaviour_ok": behaviour_ok,
108
+ "unsupported": (not abst) and (exp_abst or (kws and not any(kw_hits))),
109
+ "faithfulness": faith, "grounded_faithfulness": gfaith,
110
+ "answer_relevance": (relevance_fn(q["question"], answer) if (relevance_fn and not abst) else None),
111
+ "citation_support": cite_acc,
112
+ "precision_at_k": p_at_k, "recall_at_k": r_at_k, "mrr": rr,
113
+ "context_precision": ctx_precision, "context_recall": ctx_recall,
114
+ "confidence": r.get("confidence"),
115
+ "t_total": r["timings"]["total"], "t_retrieval": r["timings"]["retrieval"] + r["timings"].get("rerank", 0),
116
+ "t_generation": r["timings"]["generation"], "t_verification": r["timings"].get("verification", 0.0),
117
+ "explanation": r.get("explanation", ""),
118
+ "retrieved": "; ".join(f"{d} p.{p}" for d, p in units),
119
+ }
120
+
121
+
122
+ def c_doc_id(c, ctx):
123
+ for p in ctx:
124
+ if p["n"] == c["n"]:
125
+ return p["doc_id"]
126
+ return ""
127
+
128
+
129
+ def _mean(xs):
130
+ xs = [x for x in xs if x is not None]
131
+ return round(st.mean(xs), 4) if xs else None
132
+
133
+
134
+ def _prf(pred, gold):
135
+ tp = sum(p and g for p, g in zip(pred, gold))
136
+ fp = sum(p and not g for p, g in zip(pred, gold))
137
+ fn = sum((not p) and g for p, g in zip(pred, gold))
138
+ prec = tp / (tp + fp) if tp + fp else 0.0
139
+ rec = tp / (tp + fn) if tp + fn else 0.0
140
+ f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
141
+ acc = sum(p == g for p, g in zip(pred, gold)) / max(1, len(gold))
142
+ return round(prec, 4), round(rec, 4), round(f1, 4), round(acc, 4)
143
+
144
+
145
+ def aggregate(rows: list[dict]) -> dict:
146
+ ap, ar, af, aa = _prf([r["abstained"] for r in rows], [r["expected_behaviour"] == "abstain" for r in rows])
147
+ cp, cr, cf, ca = _prf([r["conflict_flagged"] for r in rows], [r["expected_status"] == "conflicting" for r in rows])
148
+ out = {
149
+ "n_questions": len(rows),
150
+ # retrieval
151
+ "precision_at_k": _mean(r["precision_at_k"] for r in rows),
152
+ "recall_at_k": _mean(r["recall_at_k"] for r in rows),
153
+ "mrr": _mean(r["mrr"] for r in rows),
154
+ # answer quality
155
+ "answer_correctness": _mean(float(r["correct"]) for r in rows),
156
+ "faithfulness": _mean(r["faithfulness"] for r in rows),
157
+ "grounded_faithfulness": _mean(r["grounded_faithfulness"] for r in rows),
158
+ "answer_relevance": _mean(r["answer_relevance"] for r in rows),
159
+ "context_precision": _mean(r["context_precision"] for r in rows),
160
+ "context_recall": _mean(r["context_recall"] for r in rows),
161
+ # reliability
162
+ "unsupported_answer_rate": _mean(float(r["unsupported"]) for r in rows),
163
+ "abstention_accuracy": aa, "abstention_precision": ap, "abstention_recall": ar, "abstention_f1": af,
164
+ "abstention_rate": _mean(float(r["abstained"]) for r in rows),
165
+ "contradiction_precision": cp, "contradiction_recall": cr, "contradiction_f1": cf,
166
+ "contradiction_accuracy": ca,
167
+ "citation_support_accuracy": _mean(r["citation_support"] for r in rows),
168
+ "behaviour_accuracy": _mean(float(r["behaviour_ok"]) for r in rows),
169
+ # efficiency
170
+ "avg_response_time_s": _mean(r["t_total"] for r in rows),
171
+ "avg_retrieval_time_s": _mean(r["t_retrieval"] for r in rows),
172
+ "avg_generation_time_s": _mean(r["t_generation"] for r in rows),
173
+ "avg_verification_time_s": _mean(r["t_verification"] for r in rows),
174
+ }
175
+ return out
176
+
177
+
178
+ def by_category(rows: list[dict]) -> dict:
179
+ cats = sorted({r["category"] for r in rows})
180
+ return {c: {"n": sum(r["category"] == c for r in rows),
181
+ "answer_correctness": _mean(float(r["correct"]) for r in rows if r["category"] == c),
182
+ "behaviour_accuracy": _mean(float(r["behaviour_ok"]) for r in rows if r["category"] == c),
183
+ "unsupported_rate": _mean(float(r["unsupported"]) for r in rows if r["category"] == c),
184
+ "abstention_rate": _mean(float(r["abstained"]) for r in rows if r["category"] == c)}
185
+ for c in cats}
186
+
187
+
188
+ def classify_error(r: dict) -> str:
189
+ """Coarse error taxonomy used in the error analysis."""
190
+ if r["behaviour_ok"]:
191
+ return "correct"
192
+ eb = r["expected_behaviour"]
193
+ if eb == "abstain":
194
+ return "answered unanswerable question (hallucination risk)"
195
+ if r["abstained"]:
196
+ return "over-abstention (answer was available)"
197
+ if eb == "flag_conflict" and not r["conflict_flagged"]:
198
+ return "missed conflict"
199
+ if r["recall_at_k"] is not None and r["recall_at_k"] == 0:
200
+ return "retrieval failure (no gold page retrieved)"
201
+ if r["keywords_hit"] == 0:
202
+ return "wrong/irrelevant answer content"
203
+ return "incomplete answer (some key facts missing)"
src/evidence_verifier.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evidence verification layer of EvidenceGuard AI.
2
+
3
+ 1. Evidence sufficiency - is the question actually covered by the retrieved passages?
4
+ 2. Contradiction detection - do relevant passages from different documents disagree?
5
+ 3. Citation validation - is every answer sentence supported by the passage it cites?
6
+
7
+ Two interchangeable judges are provided:
8
+ * NLIJudge : cross-encoder/nli-deberta-v3-xsmall (Apache-2.0), probabilities for
9
+ contradiction / entailment / neutral.
10
+ * no NLI : rule-based checks only (numeric value mismatch, polarity/negation flip,
11
+ lexical & numeric support). Always active - NLI models are known to be weak
12
+ at comparing numbers, which dominate policy documents, so the numeric rule
13
+ is kept even when NLI is available (union of both signals).
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ import re
19
+ from dataclasses import asdict, dataclass, field
20
+
21
+ import numpy as np
22
+
23
+ import config
24
+ from src.text_utils import (DOMAIN_STOPWORDS, content_tokens, extract_facts, fact_occurrences,
25
+ fact_values, split_sentences, tokenize)
26
+
27
+ log = logging.getLogger(__name__)
28
+
29
+ _NEG = re.compile(r"\b(not|cannot|no|never|without)\b")
30
+ _UPDATE_CUE = re.compile(r"\b(supersedes?|revised to|extended to|with effect from|amendment|is revised)\b", re.I)
31
+ _BOILERPLATE = re.compile(r"Document No\.|Issued by:|Effective from", re.I)
32
+
33
+
34
+ def stem(t: str) -> str:
35
+ """Tiny suffix stripper (plural / -ed / -ing); enough to match 'electives' with 'elective'."""
36
+ if len(t) <= 3 or not t.isalpha() and "-" not in t:
37
+ return t
38
+ if t.endswith("ies") and len(t) > 4:
39
+ return t[:-3] + "y"
40
+ if t.endswith(("sses", "xes", "ches", "shes")):
41
+ return t[:-2]
42
+ if t.endswith("s") and not t.endswith(("ss", "us", "is")):
43
+ t = t[:-1]
44
+ for suf in ("ing", "ed"):
45
+ if len(t) > 5 and t.endswith(suf):
46
+ return t[: -len(suf)]
47
+ return t
48
+
49
+
50
+ def stems(text: str, drop_domain: bool = False) -> set[str]:
51
+ return {stem(t) for t in content_tokens(text, drop_domain=drop_domain)}
52
+
53
+
54
+ def topic_tokens(text: str) -> set[str]:
55
+ """Content stems without numbers - what a sentence is *about*."""
56
+ return {stem(t) for t in content_tokens(text, drop_domain=True)
57
+ if not re.match(r"^\d", t) and t not in {"inr", "per", "up", "least"}}
58
+
59
+
60
+ def is_negated(text: str) -> bool:
61
+ return bool(_NEG.search(text.lower()))
62
+
63
+
64
+ def negated_predicates(text: str) -> set[str]:
65
+ """Stems of the words a negation applies to: 'will not be accepted' -> {'accept'}."""
66
+ out = set()
67
+ for m in re.finditer(r"\b(?:not|cannot|never)\s+(?:be\s+|been\s+)?([a-z]+)", text.lower()):
68
+ w = stem(m.group(1))
69
+ out.add(w[:-2] if w.endswith("ed") else w)
70
+ return out
71
+
72
+
73
+ # ====================================================================== NLI
74
+ class NLIJudge:
75
+ def __init__(self, model_name: str = config.NLI_MODEL):
76
+ from sentence_transformers import CrossEncoder
77
+ self.model = CrossEncoder(model_name, device="cpu")
78
+ cfg = getattr(self.model, "config", None) or self.model.model.config
79
+ self.labels = {int(k): v.lower() for k, v in cfg.id2label.items()}
80
+ self.name = f"NLI cross-encoder ({model_name})"
81
+
82
+ def probs(self, pairs: list[tuple[str, str]]) -> list[dict]:
83
+ if not pairs:
84
+ return []
85
+ logits = np.asarray(self.model.predict(pairs, show_progress_bar=False), dtype="float64")
86
+ if logits.ndim == 1:
87
+ logits = logits[None, :]
88
+ e = np.exp(logits - logits.max(axis=1, keepdims=True))
89
+ p = e / e.sum(axis=1, keepdims=True)
90
+ return [{self.labels[j]: float(row[j]) for j in range(row.shape[0])} for row in p]
91
+
92
+
93
+ def load_nli(backend: str = config.EG_BACKEND):
94
+ if backend in ("full", "auto"):
95
+ try:
96
+ return NLIJudge()
97
+ except Exception as e:
98
+ if backend == "full":
99
+ raise
100
+ log.warning("NLI model unavailable (%s); using rule-based verification only", e)
101
+ return None
102
+
103
+
104
+ # ====================================================================== results
105
+ @dataclass
106
+ class Sufficiency:
107
+ status: str # sufficient | partial | insufficient
108
+ max_relevance: float
109
+ coverage: float # combined coverage score
110
+ coverage_single: float
111
+ coverage_union: float
112
+ missing_terms: list = field(default_factory=list)
113
+
114
+
115
+ @dataclass
116
+ class Conflict:
117
+ doc_a: str
118
+ title_a: str
119
+ page_a: int
120
+ issued_a: str
121
+ sentence_a: str
122
+ doc_b: str
123
+ title_b: str
124
+ page_b: int
125
+ issued_b: str
126
+ sentence_b: str
127
+ kind: str # numeric | polarity | nli
128
+ detail: str
129
+ newer: str # title of the more recent document ("" if unknown)
130
+ explicit_update: bool
131
+ passage_a: int = 0 # 1-based index in the context list
132
+ passage_b: int = 0
133
+
134
+
135
+ @dataclass
136
+ class CitationCheck:
137
+ sentence: str
138
+ cited: list
139
+ supported: bool
140
+ score: float
141
+ reason: str
142
+
143
+
144
+ # ====================================================================== verifier
145
+ class EvidenceVerifier:
146
+ def __init__(self, kb, nli: NLIJudge | None = None, thresholds: dict | None = None):
147
+ self.kb = kb
148
+ self.nli = nli
149
+ self.th = thresholds or config.load_thresholds()
150
+
151
+ @property
152
+ def name(self):
153
+ return (self.nli.name + " + numeric/polarity rules") if self.nli else \
154
+ "Rule-based verifier (numeric mismatch, polarity flip, lexical support) - offline fallback"
155
+
156
+ # ------------------------------------------------------------------ 1. sufficiency
157
+ def query_terms(self, question: str) -> list[str]:
158
+ q = list(dict.fromkeys(stem(t) for t in content_tokens(question, drop_domain=True)))
159
+ return q or list(dict.fromkeys(stem(t) for t in content_tokens(question)))
160
+
161
+ def _weight(self, term: str) -> float:
162
+ # IDF is stored for raw tokens; try stem and common surface forms.
163
+ for cand in (term, term + "s", term + "es", term + "ed", term + "ing"):
164
+ if self.kb.in_vocab(cand):
165
+ return self.kb.term_idf(cand)
166
+ return self.kb.max_idf + 1.0
167
+
168
+ def sufficiency(self, question: str, items) -> Sufficiency:
169
+ terms = self.query_terms(question)
170
+ if not items or not terms:
171
+ return Sufficiency("insufficient", 0.0, 0.0, 0.0, 0.0, terms)
172
+ w = {t: self._weight(t) for t in terms}
173
+ total = sum(w.values())
174
+ top = items[:3]
175
+ pst = [stems(f"{r.chunk.title}. {r.chunk.text}") for r in top]
176
+ single = max(sum(w[t] for t in terms if t in s) / total for s in pst)
177
+ union_set = set().union(*pst)
178
+ union = sum(w[t] for t in terms if t in union_set) / total
179
+ cov = 0.5 * single + 0.5 * union
180
+ surface = {stem(t): t for t in content_tokens(question)} # stem -> word as typed
181
+ missing = [t for t in terms if t not in union_set]
182
+ # Content words that never occur anywhere in the collection (e.g. "revaluation",
183
+ # "convocation") mean the topic itself is absent: never offer a partial answer then.
184
+ oov = [t for t in missing if not re.match(r"^\d", t) and not any(
185
+ self.kb.in_vocab(c) for c in (t, t + "s", t + "es", t + "ed", t + "ing"))]
186
+ rel = max(r.relevance for r in items)
187
+ if rel >= self.th["min_relevance"] and cov >= self.th["min_coverage"]:
188
+ status = "sufficient"
189
+ elif rel >= self.th["min_relevance"] * 0.8 and cov >= self.th["partial_coverage"] and not oov:
190
+ status = "partial"
191
+ else:
192
+ status = "insufficient"
193
+ return Sufficiency(status, float(rel), float(cov), float(single), float(union),
194
+ [surface.get(t, t) for t in missing])
195
+
196
+ def sentence_coverage(self, question: str, sentence: str) -> float:
197
+ terms = self.query_terms(question)
198
+ if not terms:
199
+ return 0.0
200
+ w = {t: self._weight(t) for t in terms}
201
+ st = stems(sentence)
202
+ return sum(w[t] for t in terms if t in st) / sum(w.values())
203
+
204
+ # ------------------------------------------------------------------ 2. contradiction detection
205
+ def expand_for_conflicts(self, question: str, items, retriever, k: int = 4):
206
+ """Conflict-search retrieval.
207
+
208
+ Competing versions of a rule are often *not* in the top-k for the question (an amendment
209
+ circular is short and phrased differently). Each of the best evidence sentences is used as
210
+ a new query; passages from OTHER documents that come back are added as conflict candidates.
211
+ """
212
+ from src.retrieval import Retrieved
213
+ if retriever is None:
214
+ return []
215
+ have = {r.chunk.chunk_id for r in items}
216
+ docs = {r.chunk.doc_id for r in items}
217
+ anchors = [a for a in sorted(self._relevant_sentences(question, items), key=lambda x: -x[3])
218
+ if a[3] >= self.th["conflict_sentence_coverage"] and (extract_facts(a[2]) or is_negated(a[2]))][:3]
219
+ extra = []
220
+ for _, r, s, _ in anchors:
221
+ for cand in retriever.retrieve(s, k):
222
+ c = cand.chunk
223
+ if c.chunk_id in have or c.doc_id == r.chunk.doc_id:
224
+ continue
225
+ sim = max((self._topic_sim(s, x) for x in split_sentences(c.text)), default=0.0)
226
+ if sim >= self.th["conflict_topic_sim"]:
227
+ have.add(c.chunk_id)
228
+ extra.append(Retrieved(c, cand.score, dense=cand.dense, sparse=cand.sparse,
229
+ rerank=r.relevance * 0.99, source="conflict-search"))
230
+ del docs
231
+ return extra
232
+
233
+ def _relevant_sentences(self, question: str, items):
234
+ """Sentences that are themselves about the question (not merely in a relevant chunk)."""
235
+ out = []
236
+ for idx, r in enumerate(items, 1):
237
+ expansion = getattr(r, "source", "") == "conflict-search"
238
+ if r.relevance < self.th["conflict_min_relevance"] and not expansion:
239
+ continue
240
+ for s in split_sentences(r.chunk.text):
241
+ if _BOILERPLATE.search(s) or len(s.split()) < 5:
242
+ continue
243
+ cov = self.sentence_coverage(question, s)
244
+ if cov >= self.th["conflict_sentence_coverage"] * 0.5:
245
+ out.append((idx, r, s, cov))
246
+ return out
247
+
248
+ @staticmethod
249
+ def _topic_sim(a: str, b: str) -> float:
250
+ """Overlap coefficient of the (number-free) content stems of two sentences."""
251
+ ta, tb = topic_tokens(a), topic_tokens(b)
252
+ if not ta or not tb:
253
+ return 0.0
254
+ return len(ta & tb) / min(len(ta), len(tb))
255
+
256
+ def _numeric_clash(self, question: str, a: str, b: str, min_shared: int = 2):
257
+ """Same kind of value, different number, described by overlapping words around it.
258
+
259
+ Two extra guards against false alarms:
260
+ * the value must be of the type the question asks about ("how many marks" -> marks);
261
+ * the question words that sit next to the value must agree in both sentences
262
+ (8 books for *research scholars* is not a conflict with 6 books for *PG students*).
263
+ """
264
+ from src.llm_generator import expected_answer_type
265
+ want = expected_answer_type(question)
266
+ qt = set(self.query_terms(question))
267
+ best = None
268
+ sa_st, sb_st = stems(a), stems(b)
269
+ for ua, va, ca in fact_occurrences(a, before=75, after=40):
270
+ if want and ua not in want:
271
+ continue
272
+ wa = topic_tokens(ca)
273
+ for ub, vb, cb in fact_occurrences(b, before=75, after=40):
274
+ if ua != ub or va == vb:
275
+ continue
276
+ if ua not in ("date", "time"):
277
+ x, y = float(va), float(vb)
278
+ if min(x, y) > 0 and max(x, y) / min(x, y) > 5: # different quantities, not versions
279
+ continue
280
+ wb = topic_tokens(cb)
281
+ shared = wa & wb
282
+ # question words describing either value must also occur in the other sentence
283
+ near_q = (wa | wb) & qt
284
+ if near_q:
285
+ missing = {t for t in near_q if not (t in sa_st and t in sb_st)}
286
+ if sum(self._weight(t) for t in missing) / sum(self._weight(t) for t in near_q) > \
287
+ self.th["conflict_subject_mismatch"]:
288
+ continue
289
+ if (len(shared) >= min_shared or shared & qt) and (best is None or len(shared) > best[0]):
290
+ best = (len(shared), f"{ua}: {va} vs {vb} (context: {', '.join(sorted(shared)[:4])})")
291
+ return best[1] if best else None
292
+
293
+ def detect_conflicts(self, question: str, items) -> list[Conflict]:
294
+ sents = self._relevant_sentences(question, items)
295
+ best_cov = max((x[3] for x in sents), default=0.0)
296
+ pairs = []
297
+ for i in range(len(sents)):
298
+ for j in range(i + 1, len(sents)):
299
+ (ia, ra, sa, ca_), (ib, rb, sb, cb_) = sents[i], sents[j]
300
+ if ra.chunk.doc_id == rb.chunk.doc_id:
301
+ continue
302
+ # one side must be (close to) the best-matching evidence sentence
303
+ if max(ca_, cb_) < max(self.th["conflict_sentence_coverage"], 0.8 * best_cov):
304
+ continue
305
+ pairs.append((self._topic_sim(sa, sb), ia, ra, sa, ib, rb, sb, sents[i][3] + sents[j][3]))
306
+ # Most query-relevant pairs first, so the reported conflict is the one the user asked about.
307
+ pairs.sort(key=lambda p: -p[7])
308
+ pairs = [p[:7] for p in pairs]
309
+ nli_probs = []
310
+ if self.nli and pairs:
311
+ nli_probs = self.nli.probs([(p[3], p[6]) for p in pairs])
312
+ found, seen = [], set()
313
+ for k, (sim, ia, ra, sa, ib, rb, sb) in enumerate(pairs):
314
+ kind, detail = None, ""
315
+ clash = self._numeric_clash(question, sa, sb, int(self.th["conflict_min_shared"]))
316
+ if clash:
317
+ kind, detail = "numeric", clash
318
+ elif is_negated(sa) != is_negated(sb) and sim >= self.th["conflict_topic_sim"] and \
319
+ any(p in {x[:len(p)] for x in stems(sb if is_negated(sa) else sa)}
320
+ for p in negated_predicates(sa if is_negated(sa) else sb)):
321
+ kind, detail = "polarity", "one passage permits what the other rules out"
322
+ elif nli_probs and nli_probs[k].get("contradiction", 0) >= self.th["nli_contradiction"] \
323
+ and sim >= self.th["conflict_topic_sim"]:
324
+ kind, detail = "nli", f"NLI contradiction p={nli_probs[k]['contradiction']:.2f}"
325
+ if not kind:
326
+ continue
327
+ key = tuple(sorted([ra.chunk.doc_id, rb.chunk.doc_id]))
328
+ if key in seen:
329
+ continue
330
+ seen.add(key)
331
+ ca, cb = ra.chunk, rb.chunk
332
+ newer = ""
333
+ if ca.issued and cb.issued and ca.issued != cb.issued:
334
+ newer = ca.title if ca.issued > cb.issued else cb.title
335
+ explicit = bool(_UPDATE_CUE.search(sa) or _UPDATE_CUE.search(sb) or
336
+ _UPDATE_CUE.search(ca.text) and ca.issued >= cb.issued or
337
+ _UPDATE_CUE.search(cb.text) and cb.issued >= ca.issued)
338
+ found.append(Conflict(ca.doc_id, ca.title, ca.page, ca.issued, sa,
339
+ cb.doc_id, cb.title, cb.page, cb.issued, sb,
340
+ kind, detail, newer, explicit, ia, ib))
341
+ return found[:3]
342
+
343
+ # ------------------------------------------------------------------ 3. citation validation
344
+ def _lexical_support(self, sentence: str, passage: str) -> tuple[float, str]:
345
+ s_vals, p_vals = fact_values(sentence), fact_values(passage)
346
+ missing_vals = s_vals - p_vals
347
+ st = stems(re.sub(r"\[\d+\]", "", sentence))
348
+ pt = stems(passage)
349
+ overlap = len(st & pt) / max(1, len(st))
350
+ if missing_vals:
351
+ return min(overlap, 0.2), f"values {sorted(missing_vals)} not found in cited passage"
352
+ return overlap, f"token overlap {overlap:.2f}"
353
+
354
+ def validate_citations(self, claims, items) -> list[CitationCheck]:
355
+ checks = []
356
+ texts = [f"{r.chunk.title}. {r.chunk.text}" for r in items]
357
+ nli_inputs = []
358
+ for sent, cited in claims:
359
+ cited_ok = [c for c in cited if 1 <= c <= len(items)]
360
+ pool = cited_ok or list(range(1, len(items) + 1))
361
+ best, reason, best_c = -1.0, "no passage", []
362
+ for c in pool:
363
+ sc, why = self._lexical_support(sent, texts[c - 1])
364
+ if sc > best:
365
+ best, reason, best_c = sc, why, [c]
366
+ checks.append(CitationCheck(sent, cited_ok, best >= self.th["citation_overlap"], float(best),
367
+ reason if cited_ok else "uncited sentence; " + reason))
368
+ nli_inputs.append((texts[best_c[0] - 1] if best_c else "", sent))
369
+ if self.nli and checks:
370
+ probs = self.nli.probs([(p, re.sub(r"\[\d+\]", "", h)) for p, h in nli_inputs])
371
+ for chk, pr in zip(checks, probs):
372
+ ent = pr.get("entailment", 0.0)
373
+ if not chk.supported and ent >= self.th["nli_entailment"] and "not found" not in chk.reason:
374
+ chk.supported, chk.reason = True, chk.reason + f"; NLI entailment {ent:.2f}"
375
+ else:
376
+ chk.reason += f"; NLI entailment {ent:.2f}"
377
+ return checks
378
+
379
+ # ------------------------------------------------------------------ premise check
380
+ @staticmethod
381
+ def premise_issues(question: str, evidence_sentences: list[str]) -> list[str]:
382
+ """Values asserted in the question that the evidence states differently.
383
+
384
+ For every value in the question (e.g. "50 marks" in "Given that internal assessment
385
+ carries 50 marks ...") find the evidence value of the same unit whose surrounding words
386
+ best match the question's words around it; report it if the numbers differ.
387
+ """
388
+ issues = []
389
+ for uq, vq, cq in fact_occurrences(question, before=45, after=30):
390
+ wq = topic_tokens(cq)
391
+ best = None
392
+ for s in evidence_sentences:
393
+ for ue, ve, ce in fact_occurrences(s, before=45, after=30):
394
+ if ue != uq:
395
+ continue
396
+ shared = len(wq & topic_tokens(ce))
397
+ if shared >= 1 and (best is None or shared > best[0]):
398
+ best = (shared, ve)
399
+ if best and best[1] != vq:
400
+ unit = "" if uq == "%" else f" {uq}"
401
+ issues.append(f"the question assumes {vq}{unit}, but the documents state {best[1]}{unit}")
402
+ return issues
403
+
404
+
405
+ def to_dict(obj):
406
+ return asdict(obj) if hasattr(obj, "__dataclass_fields__") else obj
407
+
408
+
409
+ __all__ = ["EvidenceVerifier", "load_nli", "Sufficiency", "Conflict", "CitationCheck", "to_dict",
410
+ "DOMAIN_STOPWORDS", "tokenize"]
src/llm_generator.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Answer generation.
2
+
3
+ Backends
4
+ HFInferenceGenerator - Hugging Face Inference Providers (huggingface_hub.InferenceClient),
5
+ token read from the HF_TOKEN environment variable / Space secret.
6
+ LocalLLMGenerator - small instruction-tuned model (default Qwen/Qwen2.5-0.5B-Instruct,
7
+ Apache-2.0) run on CPU with transformers, greedy decoding.
8
+ ExtractiveGenerator - no LLM: composes the answer from the retrieved sentences that best
9
+ cover the question (offline fallback; cannot hallucinate new text,
10
+ but can still pick an irrelevant sentence - which is exactly the
11
+ failure EvidenceGuard's verification layer is designed to catch).
12
+
13
+ Every backend returns GenOutput with a list of (sentence, [cited passage numbers]) claims,
14
+ so citation validation works the same way for all of them.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ import re
20
+ import time
21
+ from dataclasses import dataclass, field
22
+
23
+ import config
24
+ from src.text_utils import content_tokens, extract_facts, split_sentences
25
+
26
+ log = logging.getLogger(__name__)
27
+
28
+
29
+ def expected_answer_type(question: str) -> set[str]:
30
+ """Light answer-type detection (classic QA technique): which kind of value is asked for."""
31
+ q = question.lower()
32
+ m = re.search(r"\bhow many (working days|contact hours|days|books|marks|credits|minutes|semesters|years|"
33
+ r"members|weeks|months|hours)\b", q)
34
+ if m:
35
+ unit = m.group(1)
36
+ return {"days", "working days"} if unit in ("days", "working days") else {unit}
37
+ if re.search(r"\bhow many [a-z-]+", q) and not re.search(r"\bhow many (times|of)\b", q):
38
+ return {"count"} # e.g. "how many open electives": a count, not a unit value
39
+ if re.search(r"\b(timings?|what time|at what time)\b", q):
40
+ return {"time"}
41
+ if re.search(r"\b(when|what date|which date|on what date|last date|deadline|by when)\b", q):
42
+ return {"date"}
43
+ if re.search(r"\b(fee|fine|cost|amount|charged)\b", q):
44
+ return {"inr"}
45
+ if re.search(r"\b(percentage|percent)\b", q):
46
+ return {"%"}
47
+ if re.search(r"\bhow long\b", q):
48
+ return {"days", "working days", "minutes", "semesters", "years", "weeks", "months"}
49
+ if re.search(r"\bhow (many|much)\b", q):
50
+ return {"days", "working days", "books", "marks", "credits", "minutes", "semesters", "years",
51
+ "members", "%", "inr", "mb", "contact hours", "weeks", "months"}
52
+ return set()
53
+
54
+ INSUFFICIENT = "INSUFFICIENT_EVIDENCE"
55
+
56
+ BASELINE_SYSTEM = ("You are a helpful university assistant. Answer the user's question using the "
57
+ "context passages. Cite the passages you use like [1].")
58
+
59
+ GROUNDED_SYSTEM = (
60
+ "You are EvidenceGuard, a careful university policy assistant.\n"
61
+ "Rules:\n"
62
+ "1. Use ONLY the numbered context passages. Never use outside knowledge.\n"
63
+ "2. End every sentence with the passage number(s) that support it, e.g. [2].\n"
64
+ f"3. If the passages do not contain the answer, reply with exactly: {INSUFFICIENT}\n"
65
+ "4. If the passages disagree, state each version with its citation and say which document is more recent.\n"
66
+ "5. If the question contains a false assumption, correct it.\n"
67
+ "6. Answer in at most 4 short sentences."
68
+ )
69
+
70
+
71
+ @dataclass
72
+ class GenOutput:
73
+ text: str
74
+ claims: list = field(default_factory=list) # [(sentence, [passage numbers])]
75
+ backend: str = ""
76
+ seconds: float = 0.0
77
+ declined: bool = False # model itself said evidence is insufficient
78
+
79
+
80
+ def format_context(items) -> str:
81
+ lines = []
82
+ for i, r in enumerate(items, 1):
83
+ c = r.chunk
84
+ lines.append(f"[{i}] ({c.title}, page {c.page}, issued {c.issued or 'unknown'}) {c.text}")
85
+ return "\n".join(lines)
86
+
87
+
88
+ def build_messages(question: str, items, mode: str, conflicts=None, premise_notes=None):
89
+ system = GROUNDED_SYSTEM if mode == "grounded" else BASELINE_SYSTEM
90
+ user = f"Context passages:\n{format_context(items)}\n\nQuestion: {question}"
91
+ if mode == "grounded" and conflicts:
92
+ user += "\n\nVerifier note: these passages conflict: " + "; ".join(
93
+ f"[{c.passage_a}] vs [{c.passage_b}] ({c.detail}); newer document: {c.newer or 'unknown'}"
94
+ for c in conflicts)
95
+ if mode == "grounded" and premise_notes:
96
+ user += "\n\nVerifier note: " + "; ".join(premise_notes)
97
+ return [{"role": "system", "content": system}, {"role": "user", "content": user}]
98
+
99
+
100
+ def parse_claims(text: str) -> list[tuple[str, list[int]]]:
101
+ claims = []
102
+ for s in split_sentences(text.replace("\n", " ")):
103
+ cites = [int(x) for x in re.findall(r"\[(\d+)\]", s)]
104
+ clean = re.sub(r"\s*\[\d+\](?:\s*\[\d+\])*", "", s).strip()
105
+ if clean:
106
+ claims.append((clean, cites))
107
+ return claims
108
+
109
+
110
+ # ====================================================================== LLM backends
111
+ class HFInferenceGenerator:
112
+ def __init__(self, model: str = config.HF_API_MODEL, token: str | None = config.HF_TOKEN):
113
+ if not token:
114
+ raise RuntimeError("HF_TOKEN is not set")
115
+ from huggingface_hub import InferenceClient
116
+ self.client = InferenceClient(model=model, token=token, timeout=60)
117
+ self.name = f"HF Inference API ({model})"
118
+
119
+ def complete(self, messages) -> str:
120
+ r = self.client.chat_completion(messages=messages, max_tokens=config.MAX_NEW_TOKENS,
121
+ temperature=max(0.01, config.TEMPERATURE))
122
+ return r.choices[0].message.content or ""
123
+
124
+
125
+ class LocalLLMGenerator:
126
+ def __init__(self, model: str = config.LOCAL_LLM_MODEL):
127
+ import torch
128
+ from transformers import AutoModelForCausalLM, AutoTokenizer
129
+ self.torch = torch
130
+ self.tok = AutoTokenizer.from_pretrained(model)
131
+ self.model = AutoModelForCausalLM.from_pretrained(model, dtype=torch.float32)
132
+ self.model.eval()
133
+ self.name = f"Local transformers ({model}, CPU)"
134
+
135
+ def complete(self, messages) -> str:
136
+ prompt = self.tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
137
+ ids = self.tok(prompt, return_tensors="pt")
138
+ with self.torch.no_grad():
139
+ out = self.model.generate(**ids, max_new_tokens=config.MAX_NEW_TOKENS, do_sample=False,
140
+ pad_token_id=self.tok.eos_token_id)
141
+ return self.tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True).strip()
142
+
143
+
144
+ # ====================================================================== extractive backend
145
+ class ExtractiveGenerator:
146
+ name = "Extractive composer (no LLM) - offline fallback"
147
+
148
+ def __init__(self, kb):
149
+ self.kb = kb
150
+
151
+ def select(self, question: str, items, max_sents: int = 3):
152
+ from src.evidence_verifier import stem, stems
153
+ q = list(dict.fromkeys(stem(t) for t in content_tokens(question, drop_domain=True)))
154
+ q = q or list(dict.fromkeys(stem(t) for t in content_tokens(question)))
155
+ if not items:
156
+ return []
157
+ w = {t: (self.kb.term_idf(t) if self.kb.in_vocab(t) else self.kb.max_idf) * (0.4 if t[:1].isdigit() else 1.0)
158
+ for t in q}
159
+ total = sum(w.values()) or 1.0
160
+ want = expected_answer_type(question)
161
+ cands = []
162
+ for i, r in enumerate(items, 1):
163
+ for s in split_sentences(r.chunk.text):
164
+ if re.search(r"Document No\.|Issued by:|^Aranya Valley University", s) or len(s.split()) < 6:
165
+ continue
166
+ units = {f.split(":", 1)[0] for f in extract_facts(s)}
167
+ bonus = 0.15 if want and (want & units) else 0.0
168
+ cands.append((i, r, s, stems(s), bonus))
169
+ if not cands:
170
+ return []
171
+ chosen, covered = [], set()
172
+ for _ in range(max_sents):
173
+ best, best_gain = None, 0.0
174
+ for i, r, s, st, bonus in cands:
175
+ if any(s == c[0] for c in chosen):
176
+ continue
177
+ gain = sum(w[t] for t in q if t in st and t not in covered) / total
178
+ score = gain + 0.15 * r.relevance - 0.02 * (i - 1) + (bonus if not chosen else 0.0)
179
+ if best is None or score > best[0]:
180
+ best, best_gain = (score, i, s, st), gain
181
+ if best is None or (chosen and best_gain < 0.12):
182
+ break
183
+ chosen.append((best[2], [best[1]]))
184
+ covered |= {t for t in q if t in best[3]}
185
+ return chosen
186
+
187
+
188
+ # ====================================================================== facade
189
+ class AnswerGenerator:
190
+ """Chooses an LLM backend once and exposes generate(question, items, mode, ...)."""
191
+
192
+ def __init__(self, kb, backend: str = config.LLM_BACKEND):
193
+ self.extractive = ExtractiveGenerator(kb)
194
+ self.llm = None
195
+ self.requested = backend
196
+ self.error = ""
197
+ if backend in ("auto", "hf_api") and config.HF_TOKEN:
198
+ try:
199
+ self.llm = HFInferenceGenerator()
200
+ except Exception as e:
201
+ self.error = f"HF API unavailable: {e}"
202
+ if self.llm is None and backend in ("auto", "local"):
203
+ try:
204
+ self.llm = LocalLLMGenerator()
205
+ except Exception as e:
206
+ self.error = (self.error + "; " if self.error else "") + f"local LLM unavailable: {e}"
207
+ if self.llm is None and backend not in ("extractive", "auto"):
208
+ log.warning("Requested LLM backend %s unavailable (%s); using extractive", backend, self.error)
209
+
210
+ @property
211
+ def name(self):
212
+ return self.llm.name if self.llm else self.extractive.name
213
+
214
+ def generate(self, question: str, items, mode: str = "baseline", conflicts=None,
215
+ premise_notes=None) -> GenOutput:
216
+ t0 = time.perf_counter()
217
+ if self.llm is not None:
218
+ try:
219
+ text = self.llm.complete(build_messages(question, items, mode, conflicts, premise_notes))
220
+ declined = INSUFFICIENT in text
221
+ claims = [] if declined else parse_claims(text)
222
+ return GenOutput(text, claims, self.llm.name, time.perf_counter() - t0, declined)
223
+ except Exception as e: # network / quota errors -> graceful fallback
224
+ log.warning("LLM call failed (%s); falling back to extractive", e)
225
+ return self._extractive(question, items, mode, conflicts, premise_notes, t0)
226
+
227
+ def _extractive(self, question, items, mode, conflicts, premise_notes, t0) -> GenOutput:
228
+ if mode == "grounded" and conflicts:
229
+ claims = []
230
+ for c in conflicts[:2]:
231
+ claims.append((c.sentence_a, [c.passage_a]))
232
+ claims.append((c.sentence_b, [c.passage_b]))
233
+ # add the best directly relevant sentence(s) too, so the answer stays on the question
234
+ claims += self.extractive.select(question, items, max_sents=2)
235
+ seen, uniq = set(), []
236
+ for s, ci in claims:
237
+ if s not in seen:
238
+ uniq.append((s, ci))
239
+ seen.add(s)
240
+ claims = uniq
241
+ else:
242
+ claims = self.extractive.select(question, items)
243
+ text = " ".join(f"{s} [{','.join(map(str, c))}]" for s, c in claims)
244
+ return GenOutput(text, claims, self.extractive.name, time.perf_counter() - t0)