Spaces:
Running on Zero
Running on Zero
Upload 55 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+2
- README.md+136-5
- app.pyAdded+524
- assets/architecture.pngAdded
- assets/workflow.pngAdded
- config.pyAdded+104
- requirements.txtAdded+19
- results/calibrated_thresholds.jsonAdded+51
- results/category_breakdown.csvAdded+21
- results/charts/answer_quality_comparison.pngAdded
- results/charts/category_breakdown.pngAdded
- results/charts/error_analysis.pngAdded
- results/charts/reliability_comparison.pngAdded
- results/charts/response_time.pngAdded
- results/charts/retrieval_comparison.pngAdded
- results/error_analysis.csvAdded+7
- results/failure_cases.jsonAdded+584
- results/metrics.csvAdded+13
- results/metrics.jsonAdded+537
- results/per_question_results.csvAdded
- results/significance.jsonAdded+158
- scripts/build_report.pyAdded+492
- scripts/corpus_content.pyAdded+618
- scripts/generate_dataset.pyAdded+156
- scripts/make_diagrams.pyAdded+130
- scripts/questions_spec.pyAdded+334
- scripts/render_report_docx.jsAdded+139
- scripts/run_evaluation.pyAdded+316
- scripts/significance.pyAdded+57
- src/__init__.pyAdded
- src/__pycache__/__init__.cpython-312.pycAdded
- src/__pycache__/baseline_rag.cpython-312.pycAdded
- src/__pycache__/document_processor.cpython-312.pycAdded
- src/__pycache__/embeddings.cpython-312.pycAdded
- src/__pycache__/enhanced_rag.cpython-312.pycAdded
- src/__pycache__/evidence_verifier.cpython-312.pycAdded
- src/__pycache__/llm_generator.cpython-312.pycAdded
- src/__pycache__/reranker.cpython-312.pycAdded
- src/__pycache__/research.cpython-312.pycAdded
- src/__pycache__/retrieval.cpython-312.pycAdded
- src/__pycache__/system.cpython-312.pycAdded
- src/__pycache__/text_utils.cpython-312.pycAdded
- src/__pycache__/vector_store.cpython-312.pycAdded
- src/baseline_rag.pyAdded+60
- src/document_processor.pyAdded+154
- src/embeddings.pyAdded+71
- src/enhanced_rag.pyAdded+174
- src/evaluation.pyAdded+203
- src/evidence_verifier.pyAdded+410
- src/llm_generator.pyAdded+244
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textassets/architecture.png filter=lfs diff=lfs merge=lfs -textassets/workflow.png filter=lfs diff=lfs merge=lfs -text
1234567891011121314---title: EvidenceGuard AIemoji: 👁colorFrom: bluecolorTo: indigosdk: gradiosdk_version: 6.32.0python_version: '3.12'app_file: app.pypinned: falselicense: mit---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145---title: EvidenceGuard AIemoji: 🛡️colorFrom: bluecolorTo: yellowsdk: gradiosdk_version: 6.32.0python_version: "3.12"app_file: app.pypinned: falselicense: apache-2.0short_description: Evidence-verified RAG assistant for university rules---# 🛡️ EvidenceGuard AI – Your Verified University Knowledge Assistant**A reliable university knowledge assistant using RAG, LLMs and evidence verification.**Standard RAG chatbots answer *every* question, even when the documents do not contain the answer or when twodocuments give different versions of the same rule. EvidenceGuard AI checks that **sufficient and consistentevidence** exists before answering. Otherwise it gives a partial answer, shows both conflicting versions (andnames the newer document), or abstains and explains why.> ⚠️ **All bundled documents are SYNTHETIC DEMONSTRATION DATA** describing *Aranya Valley University*, a> fictional institution. They are not real university policies, and the experimental results do not establish> real-world policy accuracy.## What's inside| Path | Contents ||---|---|| `app.py` | 7-tab Gradio app (Home, Upload, AI Assistant, Evidence Verification, Model Comparison, Evaluation Dashboard, About) || `config.py` | Models, backends, thresholds (all overridable by environment variables / Space secrets) || `src/` | `document_processor`, `embeddings`, `vector_store`, `retrieval`, `reranker`, `evidence_verifier`, `llm_generator`, `baseline_rag`, `enhanced_rag`, `evaluation`, `system`, `research`, `text_utils` || `sample_data/` | 16 generated PDFs (28 pages) + `corpus_manifest.json` || `evaluation_data/` | `questions.json` / `questions.csv`: 100 questions with evidence document, page, status and behaviour || `results/` | `metrics.csv`, `metrics.json`, per-question results, category breakdown, error analysis, failure cases, significance tests, `charts/` || `reports/` | `project_report.pdf`, `project_report.docx` || `assets/` | `architecture.png`, `workflow.png` || `docs/` | `TEST_REPORT.md`, `screenshots/` || `scripts/` | dataset generator, evaluation runner, significance tests, diagram and report builders || `tests/` | pytest suite (20 tests) |## Two systems**System A – Baseline RAG:** PDF ingestion → extraction → cleaning → chunking → Sentence-Transformer embeddings → FAISS → semantic retrieval → LLM answer → source citations.**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).## Models (free, open licences – verify on each model card)| Role | Default model | Offline fallback ||---|---|---|| Embeddings | `sentence-transformers/all-MiniLM-L6-v2` | LSA (TF-IDF + TruncatedSVD) || Reranker | `cross-encoder/ms-marco-MiniLM-L-6-v2` | lexical cross-scorer || NLI | `cross-encoder/nli-deberta-v3-xsmall` | numeric-value & polarity rules || LLM (local CPU) | `Qwen/Qwen2.5-0.5B-Instruct` | extractive composer (no LLM) || LLM (API, optional) | `Qwen/Qwen2.5-7B-Instruct` via HF Inference Providers (`HF_TOKEN`) | – |`EG_BACKEND=auto` (default) loads the Hugging Face models and falls back component-by-component if one cannotbe loaded. `EG_BACKEND=lite` forces the offline components (fast, no downloads).## Run locally```bashpython -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activatepip install -r requirements.txtpython app.py # http://127.0.0.1:7860```Fully offline / fastest start: `EG_BACKEND=lite LLM_BACKEND=extractive python app.py`Regenerate everything:```bashpython scripts/generate_dataset.py # PDFs + 100 questionspython scripts/run_evaluation.py --backend lite --llm extractive # results/ + charts (≈25 s on CPU)python scripts/significance.py # McNemar + bootstrap CIspython scripts/make_diagrams.py # assets/*.pngpip install -r requirements-dev.txt && python -m pytest -q # testspython scripts/build_report.py # reports/*.docx + *.pdf (needs Node `docx` + LibreOffice)```With the Hugging Face model stack (e.g. on Kaggle/Colab or the Space):`python scripts/run_evaluation.py --backend full --llm local` (or `--llm hf_api` with `HF_TOKEN` set). Thresholdsare re-calibrated on the DEV split for that backend automatically.## Results (real, from `results/metrics.json`)<!-- RESULTS_START -->Held-out TEST split (71 questions), backend `lite` (offline fallback components), run 2026-11-19 07:51:| Metric | Baseline RAG | + Reranking | + Verification | EvidenceGuard ||---|---|---|---|---|| Recall@5 | 0.975 | 0.992 | 0.983 | 0.992 || MRR | 0.975 | 0.958 | 0.975 | 0.958 || Answer correctness | 0.563 | 0.549 | 0.704 | 0.704 || Expected-behaviour accuracy | 0.535 | 0.521 | 0.704 | 0.704 || Evidence-grounded faithfulness | 0.770 | 0.747 | 0.858 | 0.844 || Unsupported answer rate ↓ | 0.211 | 0.225 | 0.099 | 0.099 || Abstention F1 | 0.000 | 0.000 | 0.588 | 0.588 || Contradiction F1 | 0.000 | 0.000 | 0.720 | 0.720 || Citation support accuracy | 0.756 | 0.730 | 0.826 | 0.812 || Avg response time (s) | 0.0014 | 0.0023 | 0.0040 | 0.0052 |Paired exact McNemar test, baseline vs EvidenceGuard (test split): behaviour accuracy +0.169 (p = 0.029); unsupported answers -0.113 (p = 0.039).<!-- RESULTS_END -->**Read these honestly:** gains come from the verification layer. Reranking alone gave no improvement on thissmall corpus. EvidenceGuard over-abstains on some answerable multi-part questions. The reported run used the**offline fallback components**, because Hugging Face downloads were blocked in the build environment; re-run with`--backend full` to measure the Hugging Face model stack. The verification rules were developed on the samequestion set (only thresholds were calibrated on the DEV split), so the test numbers are optimistic.## Deploy to Hugging Face Spaces1. Create a Space at <https://huggingface.co/new-space>: SDK **Gradio**, hardware **CPU basic (free)**.2. Push this repository to it:```bashgit remote add space https://huggingface.co/spaces/<your-username>/EvidenceGuard-AIgit push space main```(Authenticate with a Hugging Face **write** token as the password, or use `huggingface-cli login`.)PDFs and PNGs are binary: if the push is rejected, run `git lfs install && git lfs track "*.pdf" "*.png"` and commit again.3. Optional **Settings → Variables and secrets**:- `HF_TOKEN` (secret) – enables the stronger LLM through Hugging Face Inference Providers- `LLM_BACKEND` = `hf_api` | `local` | `extractive` (default `auto`)- `EG_BACKEND` = `auto` | `full` | `lite`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.Sample data is in the repository, so it is reloaded on every restart.Never commit tokens; `config.py` reads credentials only from environment variables.## Research basis (verified)Chen et al. (AAAI 2024, RGB) · Asai et al. (ICLR 2024, Self-RAG) · Yan et al. (arXiv 2024, CRAG) ·Gao et al. (EMNLP 2023, ALCE) · Yoran et al. (ICLR 2024) · Hou et al. (NeurIPS 2024 D&B, WikiContradict) ·Es et al. (EACL 2024 demos, RAGAS) · Niu et al. (ACL 2024, RAGTruth). Full table and IEEE references are in the reportand in the app's About tab.## LicenceCode: Apache-2.0. Generated documents and questions: synthetic, free to reuse with the "synthetic" label kept.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524"""EvidenceGuard AI - Your Verified University Knowledge AssistantGradio application (entry point for local runs and Hugging Face Spaces).
python app.py -> http://127.0.0.1:7860"""from __future__ import annotations
import jsonimport loggingimport reimport shutilimport subprocessimport sysimport threadingfrom pathlib import Path
import gradio as grimport pandas as pd
import configfrom src.research import FOUNDATION, FUTURE, LIMITATIONS, OBJECTIVES, PAPERS, RESEARCH_GAPfrom src.system import CONFIG_NAMES, EvidenceGuardSystem
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")log = logging.getLogger("app")
SYSTEM = EvidenceGuardSystem() # loads models (or fallbacks) + the synthetic sample corpusLOCK = threading.Lock() # uploads rebuild the shared indexASSETS = config.ROOT / "assets"
EXAMPLES = [ "What is the minimum attendance required to appear for end-semester examinations?", "How many books can a postgraduate student borrow from the library?", "What is the fee for revaluation of answer scripts?", "Given that internal assessment carries 50 marks, how many marks does the end-semester examination carry?", "What is the late fee for course registration?", "Are late assignment submissions accepted?", "When is Internal Test 1 held this semester, and what must a student do to take a make-up test if they miss it through illness?",]
DECISION_BADGE = { "answered": "✅ Answered - evidence verified", "partial": "🟡 Partially answered - some parts not covered", "conflict": "⚠️ Conflicting evidence - both versions shown", "abstained": "⛔ Abstained - insufficient evidence",}
# ============================================================================ helpers
def kb_table() -> pd.DataFrame: rows = [{"Document": d.doc_name, "Title": d.title, "Issued": d.issued or "-", "Pages": d.pages, "Chunks": d.chunks, "Status": d.status} for d in SYSTEM.kb.docs.values()] return pd.DataFrame(rows, columns=["Document", "Title", "Issued", "Pages", "Chunks", "Status"])
def kb_summary() -> str: n_docs, n_chunks = len(SYSTEM.kb.docs), len(SYSTEM.kb.chunks) pages = sum(d.pages for d in SYSTEM.kb.docs.values()) return f"**Knowledge base:** {n_docs} documents · {pages} pages · {n_chunks} chunks indexed in FAISS + BM25."
def msg_text(m) -> str: """Gradio 6 returns message content either as a string or as a list of typed parts.""" c = m.get("content") if isinstance(m, dict) else m if isinstance(c, str): return c if isinstance(c, dict): return c.get("text", "") if isinstance(c, (list, tuple)): return " ".join(msg_text({"content": x}) for x in c) return str(c or "")
def contextualize(question: str, history: list) -> str: """Follow-up support: short / referential questions inherit the previous user question.""" prev = [msg_text(m) for m in history if isinstance(m, dict) and m.get("role") == "user"] if not prev: return question q = question.strip() referential = re.match(r"^(and|what about|how about|also|then)\b", q, re.I) or \ re.search(r"\b(it|that|this|those|them|they|same)\b", q, re.I) if referential or len(q.split()) <= 5: last = prev[-1] last = last.split("\n(Interpreted as:")[0] return f"{q} (context: {last})" return question
def citations_md(res: dict) -> str: if not res.get("citations"): return "" lines = [f"[{c['n']}] {c['title']} - *{c['doc_name']}*, page {c['page']}" for c in res["citations"]] return "\n\n**Sources:**\n" + "\n".join(f"- {x}" for x in lines)
def answer_md(res: dict, show_badge: bool = True) -> str: label = DECISION_BADGE.get(res["decision"], res["decision"]) if res.get("sufficiency") is None and res["decision"] == "answered": label = "ℹ️ Answered without verification (baseline - may be unsupported)" badge = f"**{label}**\n\n" if show_badge else "" conf = f"\n\n<sub>Confidence: {res['confidence']:.2f} · {res['explanation']}</sub>" \ if res.get("confidence") is not None else f"\n\n<sub>{res['explanation']}</sub>" return badge + res["answer"] + citations_md(res) + conf
def passages_df(res: dict) -> pd.DataFrame: rows = [] for p in res.get("passages", []): rows.append({"#": p["n"], "Document": p["title"], "File": p["doc_name"], "Page": p["page"], "Retrieval relevance": p["relevance"], "Dense": p["dense"], "BM25": p["sparse"], "Source": p.get("source", "retrieval"), "Passage": p["text"][:400] + ("..." if len(p["text"]) > 400 else "")}) return pd.DataFrame(rows)
def verification_md(res: dict | None) -> str: if not res: return "*Ask a question in the AI Assistant tab (or below) to see its evidence report here.*" out = [f"### Question\n{res['question']}", f"### Decision\n**{DECISION_BADGE.get(res['decision'], res['decision'])}**", f"**Why:** {res['explanation']}"] s = res.get("sufficiency") if s: out.append("### Evidence sufficiency\n" f"| Signal | Value | Threshold |\n|---|---|---|\n" f"| Best passage relevance | {s['max_relevance']:.3f} | {SYSTEM.verifier.th['min_relevance']:.2f} |\n" f"| Query coverage (combined) | {s['coverage']:.3f} | {SYSTEM.verifier.th['min_coverage']:.2f} |\n" f"| Coverage by best single passage | {s['coverage_single']:.3f} | - |\n" f"| Coverage by top-3 passages | {s['coverage_union']:.3f} | - |\n" f"| Status | **{s['status']}** | - |\n\n" + (f"Question terms not found in evidence: `{', '.join(s['missing_terms'])}`" if s["missing_terms"] else "All question terms found in the evidence.")) elif res["system"].startswith("1.") or res["system"].startswith("2."): out.append("*Baseline configuration: no sufficiency, contradiction or citation checks are performed.*") cs = res.get("conflicts") or [] out.append("### Contradiction status\n" + ("No contradiction detected between the retrieved documents." if not cs else "")) for c in cs: out.append(f"- **{c['kind']} conflict** ({c['detail']})\n" f" - *{c['title_a']}* (p.{c['page_a']}, issued {c['issued_a'] or '?'}): {c['sentence_a']}\n" f" - *{c['title_b']}* (p.{c['page_b']}, issued {c['issued_b'] or '?'}): {c['sentence_b']}\n" f" - Newer document: **{c['newer'] or 'unknown'}**" + (" (explicitly revises the earlier rule)" if c["explicit_update"] else "")) if res.get("premise_notes"): out.append("### False-premise check\n" + "\n".join(f"- {p}" for p in res["premise_notes"])) ch = res.get("citation_checks") or [] if ch: out.append("### Citation verification\n| Sentence | Cited | Supported | Score | Reason |\n|---|---|---|---|---|\n" + "\n".join(f"| {c['sentence'][:110].replace('|', '/')} | {c['cited']} | " f"{'✅' if c['supported'] else '❌'} | {c['score']:.2f} | {c['reason'][:80]} |" for c in ch)) t = res["timings"] out.append(f"### Timing\nretrieval {t['retrieval']*1000:.0f} ms · rerank {t.get('rerank', 0)*1000:.0f} ms · " f"verification {t.get('verification', 0)*1000:.0f} ms · generation {t['generation']*1000:.0f} ms · " f"**total {t['total']*1000:.0f} ms** · generator: {res.get('generator') or '-'}") return "\n\n".join(out)
# ============================================================================ callbacks
def process_uploads(files): if not files: return pd.DataFrame(), kb_table(), kb_summary(), "Please choose one or more PDF files first." paths = [] for f in files: src = Path(f if isinstance(f, str) else f.name) if src.suffix.lower() != ".pdf": continue dst = config.UPLOAD_DIR / src.name shutil.copy(src, dst) paths.append(dst) if not paths: return pd.DataFrame(), kb_table(), kb_summary(), "No PDF files were found in the upload." with LOCK: infos = SYSTEM.kb.add_pdfs(paths) rows = [{"File": i.doc_name, "Extraction status": f"{i.status}: {i.message}", "Pages": i.pages, "Chunks": i.chunks, "Detected title": i.title, "Detected date": i.issued or "-"} for i in infos] ok = sum(i.status == "ok" for i in infos) return (pd.DataFrame(rows), kb_table(), kb_summary(), f"Processed {len(infos)} file(s): {ok} indexed successfully. You can now ask questions about them.")
def reset_kb(): with LOCK: for d in list(SYSTEM.kb.docs): SYSTEM.kb.docs.pop(d) SYSTEM.kb.chunks = [] SYSTEM.kb.load_folder(config.SAMPLE_DATA_DIR) return pd.DataFrame(), kb_table(), kb_summary(), "Knowledge base reset to the 16 synthetic sample documents."
def remove_doc(name): with LOCK: for did, d in list(SYSTEM.kb.docs.items()): if d.doc_name == name: SYSTEM.kb.remove_doc(did) return kb_table(), kb_summary(), f"Removed {name}." return kb_table(), kb_summary(), f"Document '{name}' not found."
def chat(message, history, mode): history = history or [] if not message or not message.strip(): return history, "", None if not SYSTEM.kb.ready: history += [{"role": "user", "content": message}, {"role": "assistant", "content": "The knowledge base is empty. Upload PDFs in the Upload tab first."}] return history, "", None q = contextualize(message, history) key = "full" if mode.startswith("EvidenceGuard") else "baseline" with LOCK: res = SYSTEM.pipelines[key].answer(q) shown = message if q == message else f"{message}\n(Interpreted as: {q})" history += [{"role": "user", "content": shown}, {"role": "assistant", "content": answer_md(res)}] return history, "", res
def verify_direct(question, cfg): if not question.strip(): return "Please type a question.", pd.DataFrame(), None key = {v: k for k, v in CONFIG_NAMES.items()}[cfg] with LOCK: res = SYSTEM.pipelines[key].answer(question) return verification_md(res), passages_df(res), res
def show_last(res): return verification_md(res), passages_df(res) if res else pd.DataFrame()
def compare(question): if not question.strip(): empty = "Please type a question." return empty, empty, pd.DataFrame(), pd.DataFrame(), pd.DataFrame() with LOCK: a = SYSTEM.pipelines["baseline"].answer(question) b = SYSTEM.pipelines["full"].answer(question)
def perf(r, name): t = r["timings"] return {"System": name, "Decision": r["decision"], "Passages": len(r["passages"]), "Citations": len(r["citations"]), "Conflicts flagged": len(r.get("conflicts") or []), "Confidence": r.get("confidence"), "Retrieval ms": round((t["retrieval"] + t.get("rerank", 0)) * 1000, 1), "Verification ms": round(t.get("verification", 0) * 1000, 1), "Generation ms": round(t["generation"] * 1000, 1), "Total ms": round(t["total"] * 1000, 1)} perf_df = pd.DataFrame([perf(a, "Baseline RAG"), perf(b, "EvidenceGuard")]) return answer_md(a, show_badge=False), answer_md(b), passages_df(a), passages_df(b), perf_df
# ---------------------------------------------------------------------------- evaluation dashboardMETRIC_LABELS = { "precision_at_k": "Precision@5", "recall_at_k": "Recall@5", "mrr": "MRR", "answer_correctness": "Answer correctness", "behaviour_accuracy": "Expected-behaviour accuracy", "faithfulness": "Faithfulness (to context)", "grounded_faithfulness": "Evidence-grounded faithfulness", "answer_relevance": "Answer relevance (lexical proxy)", "context_precision": "Context precision (AP@5)", "context_recall": "Context recall (key facts in context)", "unsupported_answer_rate": "Unsupported answer rate ↓", "abstention_accuracy": "Abstention accuracy", "abstention_f1": "Abstention F1", "contradiction_precision": "Contradiction precision", "contradiction_recall": "Contradiction recall", "contradiction_f1": "Contradiction F1", "citation_support_accuracy": "Citation support accuracy", "avg_response_time_s": "Avg response time (s)", "avg_retrieval_time_s": "Avg retrieval time (s)", "avg_generation_time_s": "Avg generation time (s)", "avg_verification_time_s": "Avg verification time (s)",}
def load_eval(split="all"): p = config.RESULTS_DIR / "metrics.json" if not p.exists(): return pd.DataFrame({"info": ["No results yet - click 'Re-run evaluation'."]}), "", pd.DataFrame(), pd.DataFrame(), pd.DataFrame() m = json.loads(p.read_text()) names = m["config_names"] order = ["baseline", "rerank", "verify", "full"] rows = [] for k, lab in METRIC_LABELS.items(): rows.append({"Metric": lab, **{names[c]: m["metrics"][split][c].get(k) for c in order}}) meta = m["meta"] info = (f"**Run:** {meta['date']} · {meta['n_questions']} questions ({meta['dev_questions']} dev used for " f"threshold calibration, {meta['test_questions']} held-out test) · backend `{meta['backend']}` · " f"runtime {meta['runtime_s']} s\n\n**Components used in this run:** " + "; ".join(f"{k}: {v}" for k, v in meta["components"].items()) + f"\n\n> ⚠️ {meta['note']}") cat = pd.read_csv(config.RESULTS_DIR / "category_breakdown.csv") err = pd.read_csv(config.RESULTS_DIR / "error_analysis.csv") fails = json.loads((config.RESULTS_DIR / "failure_cases.json").read_text()) fdf = pd.DataFrame(fails["evidenceguard_failures"])[["id", "category", "question", "error_type", "answer", "expected_answer", "explanation"]] \ if fails["evidenceguard_failures"] else pd.DataFrame() return pd.DataFrame(rows), info, cat, err, fdf
def chart_paths(): names = ["retrieval_comparison", "answer_quality_comparison", "reliability_comparison", "category_breakdown", "error_analysis", "response_time"] return [str(config.CHARTS_DIR / f"{n}.png") if (config.CHARTS_DIR / f"{n}.png").exists() else None for n in names]
def rerun_eval(split): backend = SYSTEM.effective_backend cmd = [sys.executable, str(config.ROOT / "scripts" / "run_evaluation.py"), "--backend", backend, "--llm", "extractive" if SYSTEM.generator.llm is None else config.LLM_BACKEND] proc = subprocess.run(cmd, capture_output=True, text=True, cwd=str(config.ROOT), timeout=3600) status = ("✅ Evaluation finished." if proc.returncode == 0 else "❌ Evaluation failed:\n" + proc.stderr[-1500:]) if proc.returncode == 0: SYSTEM.set_thresholds(config.load_thresholds(SYSTEM.effective_backend)) return (status + "\n\n```\n" + proc.stdout[-1800:] + "\n```", *load_eval(split), *chart_paths())
# ============================================================================ UI textHOME_MD = f"""# 🛡️ EvidenceGuard AI### Your Verified University Knowledge Assistant
**Problem.** Ordinary LLM chatbots and standard RAG systems answer *every* question, even when thedocuments do not contain the answer, when the retrieved text is irrelevant, or when two documents give**different versions of the same rule** (e.g. an old regulation and a newer amendment circular).For students, a confident wrong answer about attendance, exam eligibility or scholarship deadlines has real consequences.
**EvidenceGuard AI** retrieves information from university documents and **verifies that sufficient,consistent evidence exists before answering**. Otherwise it gives a partial answer, shows bothconflicting versions, or refuses and explains why.
#### Key features- 📄 Upload any PDFs; text extraction, cleaning, chunking and indexing (FAISS + BM25)- 🔎 Hybrid semantic + keyword retrieval with cross-encoder reranking- 🧪 Evidence-sufficiency check → **abstains** instead of guessing- ⚖️ **Conflict search**: detects contradictions between documents and names the newer version- 🔗 **Citation validation**: every answer sentence is checked against the passage it cites- 💬 Explanations of why the system answered, partially answered or refused- 📊 Side-by-side Baseline vs EvidenceGuard comparison and a real evaluation dashboard
#### Research contributionA training-free, CPU-only verification layer combining sufficiency-based abstention, numeric-awareinter-document contradiction detection with *conflict-search retrieval*, and inference-time citationvalidation, evaluated with a 4-configuration ablation on a 100-question benchmark containing labelledmissing, misleading and conflicting questions.
> ⚠️ The bundled documents describe **Aranya Valley University, a fictional institution**. They are> SYNTHETIC DEMONSTRATION DATA, not real university policy."""
ABOUT_PARTS = []
def about_md(): lit = "| # | Paper | Authors (year) | Venue | Problem | Method | Limitation | How EvidenceGuard responds |\n|---|---|---|---|---|---|---|---|\n" for i, p in enumerate(PAPERS, 1): lit += (f"| {i} | [{p['title']}]({p['link']}) | {p['authors']} ({p['year']}) | {p['venue']} | {p['problem']} | " f"{p['method']} | {p['limitations']} | {p['ours']} |\n") refs = "\n".join(f"{i}. {p['authors']}, \"{p['title']},\" {p['venue']}. {p['link']}" for i, p in enumerate(PAPERS, 1)) refs += "\n" + "\n".join(f"{len(PAPERS) + i}. {r}" for i, r in enumerate(FOUNDATION, 1)) return f"""## Research papers (verified, 2023-2024){lit}
## Research gap{RESEARCH_GAP}
## Objectives{chr(10).join(f'{i}. {o}' for i, o in enumerate(OBJECTIVES, 1))}
## Methodology1. **Synthetic corpus** - 16 fictional AVU PDFs (28 pages) generated from one fact base, with 9 planted conflicts, superseding circulars, a distractor document and deliberately uncovered topics.2. **Benchmark** - 100 questions (30 answerable, 20 multi-passage, 15 missing-information, 15 misleading, 20 conflicting), each with expected answer, key facts, evidence document/page, expected evidence status and behaviour.3. **Systems** - Baseline RAG (dense FAISS → LLM → citations) vs EvidenceGuard (hybrid → rerank → sufficiency → conflict search & contradiction → grounded generation → citation validation → confidence/abstention).4. **Ablation** - 4 configurations; thresholds calibrated on a stratified DEV split (29 questions) only, results reported on all 100 and on the 71 held-out TEST questions.5. **Metrics** - Precision/Recall@5, MRR, answer correctness, faithfulness, answer relevance, context precision/recall, unsupported-answer rate, abstention and contradiction P/R/F1, citation support accuracy, latency.
## ArchitectureSee the diagrams below. Every model component has an offline fallback so the app runs on any CPU.
## Limitations{chr(10).join(f'- {x}' for x in LIMITATIONS)}
## Future scope{chr(10).join(f'- {x}' for x in FUTURE)}
## References (IEEE style){refs}"""
def stack_md(): rows = "\n".join(f"| {k} | {v} |" for k, v in SYSTEM.component_names().items()) return ("#### Technology stack (live - what this running instance is using)\n| Component | Implementation |\n|---|---|\n" + rows + "\n| UI | Gradio |\n| PDF processing | PyMuPDF (pypdf fallback) |\n\n" "If a Hugging Face model cannot be downloaded, the app automatically uses the offline fallback shown here.")
CSS = """.gradio-container {max-width: 1280px !important}.badge {font-size: 0.9em}footer {visibility: hidden}"""
# ============================================================================ layoutwith gr.Blocks(title="EvidenceGuard AI") as demo: last_result = gr.State(None) gr.Markdown("<h2 style='margin:0'>🛡️ EvidenceGuard AI - Your Verified University Knowledge Assistant</h2>" "<span style='color:#b00020;font-size:0.85em'>Demo corpus = SYNTHETIC DEMONSTRATION DATA of a fictional university</span>")
# ---------------------------------------------------------------- TAB 1 with gr.Tab("🏠 Home"): with gr.Row(): with gr.Column(scale=3): gr.Markdown(HOME_MD) with gr.Column(scale=2): gr.Markdown(stack_md()) home_kb = gr.Markdown(kb_summary()) gr.Markdown("#### System workflow") gr.Image(str(ASSETS / "workflow.png"), show_label=False, height=620)
# ---------------------------------------------------------------- TAB 2 with gr.Tab("📄 Upload Documents"): gr.Markdown("Upload one or more PDFs. They are extracted, cleaned, chunked and added to the FAISS + BM25 index " "alongside the sample documents. Re-uploading a file with the same name replaces it.") with gr.Row(): up_files = gr.File(label="PDF files", file_count="multiple", file_types=[".pdf"]) with gr.Column(): up_btn = gr.Button("⚙️ Process documents into the vector database", variant="primary") reset_btn = gr.Button("↩️ Reset to sample data") up_status = gr.Markdown() up_result = gr.Dataframe(label="Processing result (this upload)", interactive=False) up_kb_md = gr.Markdown(kb_summary()) up_kb = gr.Dataframe(value=kb_table(), label="Documents in the knowledge base", interactive=False) with gr.Row(): rm_name = gr.Textbox(label="Remove a document (file name)", placeholder="e.g. my_policy.pdf") rm_btn = gr.Button("🗑️ Remove")
# ---------------------------------------------------------------- TAB 3 with gr.Tab("💬 AI Assistant"): with gr.Row(): mode = gr.Radio(["EvidenceGuard (verified)", "Baseline RAG"], value="EvidenceGuard (verified)", label="Answering system") chatbot = gr.Chatbot(height=470, label="EvidenceGuard Assistant", render_markdown=True) with gr.Row(): msg = gr.Textbox(placeholder="Ask about attendance, exams, scholarships, library rules... " "(follow-up questions are supported)", scale=6, show_label=False) send = gr.Button("Ask", variant="primary", scale=1) clear = gr.Button("Clear chat", scale=1) gr.Examples(EXAMPLES, inputs=msg, label="Try these (include missing-information, misleading and conflicting cases)") gr.Markdown("*The full evidence report for the latest answer is in the **Evidence Verification** tab.*")
# ---------------------------------------------------------------- TAB 4 with gr.Tab("🔬 Evidence Verification"): gr.Markdown("Shows the retrieved passages, sources, pages, relevance scores, evidence sufficiency, " "contradiction status, citation verification and the reason for any abstention.") with gr.Row(): v_q = gr.Textbox(label="Question", placeholder="Type a question, or press 'Show latest chat answer'", scale=4) v_cfg = gr.Dropdown(list(CONFIG_NAMES.values()), value=CONFIG_NAMES["full"], label="Configuration", scale=2) with gr.Row(): v_btn = gr.Button("🔍 Verify this question", variant="primary") v_last = gr.Button("Show latest chat answer") v_md = gr.Markdown(verification_md(None)) v_df = gr.Dataframe(label="Retrieved passages", interactive=False, wrap=True)
# ---------------------------------------------------------------- TAB 5 with gr.Tab("⚖️ Model Comparison"): with gr.Row(): c_q = gr.Textbox(label="Question", scale=5, value=EXAMPLES[0]) c_btn = gr.Button("Compare", variant="primary", scale=1) gr.Examples(EXAMPLES, inputs=c_q) with gr.Row(): with gr.Column(): gr.Markdown("### System A - Baseline RAG") c_a = gr.Markdown() c_pa = gr.Dataframe(label="Baseline evidence", interactive=False, wrap=True) with gr.Column(): gr.Markdown("### System B - EvidenceGuard RAG") c_b = gr.Markdown() c_pb = gr.Dataframe(label="EvidenceGuard evidence", interactive=False, wrap=True) c_perf = gr.Dataframe(label="Performance information", interactive=False)
# ---------------------------------------------------------------- TAB 6 with gr.Tab("📊 Evaluation Dashboard"): with gr.Row(): e_split = gr.Radio(["all", "test", "dev"], value="all", label="Question split") e_reload = gr.Button("Reload results") e_run = gr.Button("▶️ Re-run evaluation (100 questions × 4 systems)", variant="primary") e_status = gr.Markdown() e_info = gr.Markdown() e_table = gr.Dataframe(label="Metrics (real values from results/metrics.json)", interactive=False) with gr.Row(): ch1 = gr.Image(label="Retrieval comparison") ch2 = gr.Image(label="Answer quality & faithfulness") with gr.Row(): ch3 = gr.Image(label="Reliability: unsupported answers, abstention, contradictions") ch4 = gr.Image(label="Behaviour accuracy by category") with gr.Row(): ch5 = gr.Image(label="Error analysis") ch6 = gr.Image(label="Response time") e_cat = gr.Dataframe(label="Category breakdown", interactive=False) e_err = gr.Dataframe(label="Error analysis (counts per configuration)", interactive=False) e_fail = gr.Dataframe(label="EvidenceGuard failure cases", interactive=False, wrap=True)
# ---------------------------------------------------------------- TAB 7 with gr.Tab("ℹ️ About Project"): gr.Markdown(about_md()) gr.Image(str(ASSETS / "architecture.png"), label="System architecture")
# ================================================================ wiring up_btn.click(process_uploads, up_files, [up_result, up_kb, up_kb_md, up_status]).then(kb_summary, None, home_kb) reset_btn.click(reset_kb, None, [up_result, up_kb, up_kb_md, up_status]).then(kb_summary, None, home_kb) rm_btn.click(remove_doc, rm_name, [up_kb, up_kb_md, up_status]) send.click(chat, [msg, chatbot, mode], [chatbot, msg, last_result]) msg.submit(chat, [msg, chatbot, mode], [chatbot, msg, last_result]) clear.click(lambda: ([], None), None, [chatbot, last_result]) v_btn.click(verify_direct, [v_q, v_cfg], [v_md, v_df, last_result]) v_last.click(show_last, last_result, [v_md, v_df]) c_btn.click(compare, c_q, [c_a, c_b, c_pa, c_pb, c_perf]) eval_outs = [e_table, e_info, e_cat, e_err, e_fail] e_reload.click(load_eval, e_split, eval_outs).then(chart_paths, None, [ch1, ch2, ch3, ch4, ch5, ch6]) e_split.change(load_eval, e_split, eval_outs) e_run.click(rerun_eval, e_split, [e_status, *eval_outs, ch1, ch2, ch3, ch4, ch5, ch6]) demo.load(load_eval, e_split, eval_outs).then(chart_paths, None, [ch1, ch2, ch3, ch4, ch5, ch6])
if __name__ == "__main__": demo.queue(default_concurrency_limit=2).launch( server_name="0.0.0.0", server_port=int(__import__("os").getenv("PORT", 7860)), theme=gr.themes.Soft(primary_hue="blue"), css=CSS, show_error=True, allowed_paths=[str(ASSETS), str(config.CHARTS_DIR)])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""Central configuration for EvidenceGuard AI.
Every value can be overridden with an environment variable (or a Hugging Face Spacesecret/variable) of the same name. No credentials are stored in code.
Backends--------EG_BACKEND = "auto" | "full" | "lite" full : Hugging Face models (Sentence Transformer, cross-encoder reranker, NLI cross-encoder) lite : dependency-light, CPU-only fallbacks (TF-IDF+SVD embeddings, lexical reranker, rule-based numeric/negation contradiction detector). Used when models cannot be downloaded (offline machines) and for fast tests. auto : try "full", fall back to "lite" component-by-component if a model cannot load.
LLM_BACKEND = "auto" | "hf_api" | "local" | "extractive" hf_api : Hugging Face Inference Providers via huggingface_hub (needs HF_TOKEN secret) local : small instruction-tuned model run locally with transformers (CPU OK) extractive : no LLM; answer is composed from retrieved sentences (fully offline) auto : hf_api if HF_TOKEN is set, else local, else extractive"""from __future__ import annotations
import osfrom pathlib import Path
ROOT = Path(__file__).resolve().parentSAMPLE_DATA_DIR = ROOT / "sample_data"EVAL_DATA_PATH = ROOT / "evaluation_data" / "questions.json"RESULTS_DIR = ROOT / "results"CHARTS_DIR = RESULTS_DIR / "charts"CACHE_DIR = Path(os.getenv("EG_CACHE_DIR", str(ROOT / ".cache")))UPLOAD_DIR = CACHE_DIR / "uploads"
def _env(name: str, default): v = os.getenv(name) if v is None or v == "": return default return type(default)(v) if not isinstance(default, bool) else v.lower() in {"1", "true", "yes"}
# ---------------------------------------------------------------- backendsEG_BACKEND = _env("EG_BACKEND", "auto")LLM_BACKEND = _env("LLM_BACKEND", "auto")
# ---------------------------------------------------------------- models (all free / open licences)EMBEDDING_MODEL = _env("EMBEDDING_MODEL", "sentence-transformers/all-MiniLM-L6-v2")RERANKER_MODEL = _env("RERANKER_MODEL", "cross-encoder/ms-marco-MiniLM-L-6-v2")NLI_MODEL = _env("NLI_MODEL", "cross-encoder/nli-deberta-v3-xsmall")LOCAL_LLM_MODEL = _env("LOCAL_LLM_MODEL", "Qwen/Qwen2.5-0.5B-Instruct")HF_API_MODEL = _env("HF_API_MODEL", "Qwen/Qwen2.5-7B-Instruct")HF_TOKEN = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACEHUB_API_TOKEN") # Space secret, never hard-coded
# ---------------------------------------------------------------- chunking & retrievalCHUNK_TARGET_WORDS = _env("CHUNK_TARGET_WORDS", 70)CHUNK_OVERLAP_SENTENCES = _env("CHUNK_OVERLAP_SENTENCES", 1)TOP_K = _env("TOP_K", 5) # passages given to the generatorCANDIDATES = _env("CANDIDATES", 20) # candidates pulled by each retriever before fusion/rerankingRRF_K = _env("RRF_K", 60)LSA_DIM = _env("LSA_DIM", 256)
# ---------------------------------------------------------------- generationMAX_NEW_TOKENS = _env("MAX_NEW_TOKENS", 220)TEMPERATURE = _env("TEMPERATURE", 0.0)
# ---------------------------------------------------------------- verification thresholds# Default values; scripts/run_evaluation.py re-calibrates them on a held-out DEV split# and writes results/calibrated_thresholds.json, which is loaded automatically if present.THRESHOLDS = { "min_relevance": _env("MIN_RELEVANCE", 0.30), # reranker score of best passage "min_coverage": _env("MIN_COVERAGE", 0.60), # IDF-weighted query-term coverage "partial_coverage": _env("PARTIAL_COVERAGE", 0.45), "min_confidence": _env("MIN_CONFIDENCE", 0.40), "conflict_topic_sim": _env("CONFLICT_TOPIC_SIM", 0.30), # overlap coefficient (polarity/NLI) "conflict_sentence_coverage": _env("CONFLICT_SENT_COV", 0.35), # sentence must cover the question "conflict_min_shared": _env("CONFLICT_MIN_SHARED", 2), # shared context words around a value "conflict_subject_mismatch": _env("CONFLICT_SUBJECT_MISMATCH", 0.30), # max weight of unshared question words "conflict_min_relevance": _env("CONFLICT_MIN_RELEVANCE", 0.25), "nli_contradiction": _env("NLI_CONTRADICTION", 0.60), "nli_entailment": _env("NLI_ENTAILMENT", 0.50), "citation_overlap": _env("CITATION_OVERLAP", 0.50),}
CALIBRATED_THRESHOLDS_PATH = RESULTS_DIR / "calibrated_thresholds.json"
def load_thresholds(effective_backend: str = "lite") -> dict: """Defaults, overridden by calibrated values only if they were calibrated for the same backend (reranker scores of the lexical fallback and of the cross-encoder live on different scales).""" import json th = dict(THRESHOLDS) if CALIBRATED_THRESHOLDS_PATH.exists() and not os.getenv("EG_IGNORE_CALIBRATION"): try: cal = json.loads(CALIBRATED_THRESHOLDS_PATH.read_text()) if cal.get("backend") == effective_backend: th.update(cal.get("thresholds", {})) except Exception: pass return th
for _d in (CACHE_DIR, UPLOAD_DIR, CHARTS_DIR): _d.mkdir(parents=True, exist_ok=True)12345678910111213141516171819# CPU-only PyTorch wheels (much smaller than the default CUDA build) - works on free HF Spaces--extra-index-url https://download.pytorch.org/whl/cpu
gradio>=6.0numpy>=1.26pandas>=2.0scikit-learn>=1.3faiss-cpu>=1.8rank-bm25>=0.2.2pymupdf>=1.24pypdf>=4.0reportlab>=4.0matplotlib>=3.8
# Hugging Face model stack (optional at runtime - the app falls back to offline components if missing)torch>=2.2transformers>=4.44sentence-transformers>=3.0huggingface_hub>=0.24123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051{ "backend": "lite", "thresholds": { "min_relevance": 0.15, "min_coverage": 0.6, "partial_coverage": 0.5, "min_confidence": 0.3, "conflict_topic_sim": 0.3, "conflict_sentence_coverage": 0.35, "conflict_min_shared": 2, "conflict_subject_mismatch": 0.3, "conflict_min_relevance": 0.25, "nli_contradiction": 0.6, "nli_entailment": 0.5, "citation_overlap": 0.5 }, "dev_ids": [ "A06", "A07", "A11", "A12", "A13", "A15", "A20", "A23", "A27", "C08", "C11", "C12", "C13", "C16", "C20", "I03", "I08", "I10", "I12", "M03", "M10", "M12", "M13", "M14", "M15", "N01", "N09", "N11", "N15" ], "dev_behaviour_accuracy": 0.7931, "dev_abstention_accuracy": 0.8966, "dev_unsupported_rate": 0.069}123456789101112131415161718192021configuration,category,n,answer_correctness,behaviour_accuracy,unsupported_rate,abstention_rate
Baseline RAG,answerable,30,1.0,1.0,0.0,0.0
Baseline RAG,conflicting,20,0.1,0.0,0.05,0.0
Baseline RAG,misleading,15,0.8,0.8,0.1333,0.0
Baseline RAG,missing,15,0.0,0.0,1.0,0.0
Baseline RAG,multi_passage,20,0.65,0.65,0.05,0.0
+ Reranking,answerable,30,1.0,1.0,0.0,0.0
+ Reranking,conflicting,20,0.1,0.0,0.05,0.0
+ Reranking,misleading,15,0.8,0.8,0.1333,0.0
+ Reranking,missing,15,0.0,0.0,1.0,0.0
+ Reranking,multi_passage,20,0.6,0.6,0.1,0.0
+ Verification,answerable,30,0.9,0.9,0.0,0.1
+ Verification,conflicting,20,0.65,0.65,0.05,0.2
+ Verification,misleading,15,0.7333,0.7333,0.1333,0.1333
+ Verification,missing,15,0.8,0.8,0.2,0.8
+ Verification,multi_passage,20,0.5,0.5,0.15,0.25
EvidenceGuard,answerable,30,0.9,0.9,0.0,0.1
EvidenceGuard,conflicting,20,0.65,0.65,0.05,0.2
EvidenceGuard,misleading,15,0.7333,0.7333,0.1333,0.1333
EvidenceGuard,missing,15,0.8,0.8,0.2,0.8
EvidenceGuard,multi_passage,20,0.5,0.5,0.15,0.251234567error_type,Baseline RAG,+ Reranking,+ Verification,EvidenceGuard
answered unanswerable question (hallucination risk),15,15,3,3
correct,55,54,73,73
incomplete answer (some key facts missing),7,7,2,2
missed conflict,20,20,3,3
over-abstention (answer was available),0,0,14,14
wrong/irrelevant answer content,3,4,5,5123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584{ "evidenceguard_failures": [ { "id": "A10", "category": "answerable", "question": "What are the timings of the afternoon examination session?", "expected_behaviour": "answer", "error_type": "over-abstention (answer was available)", "decision": "abstained", "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "expected_answer": "2:00 PM to 5:00 PM.", "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.", "retrieved": "D06 p.2; D06 p.1; D06 p.1; D06 p.1; D06 p.2", "baseline_answer": "Afternoon session: 2:00 PM to 5:00 PM. [3]", "baseline_ok": true }, { "id": "A17", "category": "answerable", "question": "What is the amount of the need-based scholarship?", "expected_behaviour": "answer", "error_type": "over-abstention (answer was available)", "decision": "abstained", "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "expected_answer": "INR 30,000 per year.", "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.", "retrieved": "D07 p.1; D08 p.1; D07 p.1; D07 p.2; D08 p.1", "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]", "baseline_ok": true }, { "id": "A24", "category": "answerable", "question": "How far in advance must an application for academic leave be submitted?", "expected_behaviour": "answer", "error_type": "over-abstention (answer was available)", "decision": "abstained", "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "expected_answer": "At least 30 days before the start of the semester (except medical emergencies).", "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.", "retrieved": "D10 p.1; D10 p.1; D07 p.1; D10 p.2; D10 p.1", "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]", "baseline_ok": true }, { "id": "M01", "category": "multi_passage", "question": "What minimum internal assessment marks are needed for exam eligibility, and how many marks is each internal test worth?", "expected_behaviour": "answer", "error_type": "over-abstention (answer was available)", "decision": "abstained", "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "expected_answer": "At least 16 out of 40 IA marks (40%); each internal test is worth 15 marks.", "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.", "retrieved": "D04 p.1; D03 p.1; D04 p.1; D04 p.2; D04 p.1", "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]", "baseline_ok": false }, { "id": "M02", "category": "multi_passage", "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?", "expected_behaviour": "answer", "error_type": "over-abstention (answer was available)", "decision": "abstained", "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "expected_answer": "1-5 September 2025; submit a medical certificate within 3 working days to take one make-up test.", "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.", "retrieved": "D04 p.1; D04 p.1; D04 p.1; D14 p.1; D14 p.1", "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]", "baseline_ok": false }, { "id": "M03", "category": "multi_passage", "question": "What happens to a student whose attendance is still short after condonation, and to whom can an eligibility decision be appealed?", "expected_behaviour": "answer", "error_type": "over-abstention (answer was available)", "decision": "abstained", "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "expected_answer": "They are marked NE (Not Eligible) and must re-register; appeals go to the Controller of Examinations within 3 working days.", "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.", "retrieved": "D03 p.2; D02 p.1; D01 p.1; D03 p.1; D01 p.1", "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]", "baseline_ok": false }, { "id": "M08", "category": "multi_passage", "question": "How many internal assessment marks are given for assignments, and in what file format must assignments be submitted?", "expected_behaviour": "answer", "error_type": "wrong/irrelevant answer content", "decision": "conflict", "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]", "expected_answer": "5 marks; as a single PDF file (max 10 MB).", "explanation": "Answered with a conflict warning: 'Internal Assessment Guidelines 2024' and 'Assignment Submission Policy 2024' disagree (one passage permits what the other rules out).", "retrieved": "D04 p.2; D05 p.1; D05 p.1; D04 p.1; D04 p.1; D14 p.1", "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]", "baseline_ok": false }, { "id": "M11", "category": "multi_passage", "question": "What documents must be submitted for the need-based scholarship, and how recent must the income certificate be?", "expected_behaviour": "answer", "error_type": "wrong/irrelevant answer content", "decision": "conflict", "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]", "expected_answer": "An income certificate from a competent authority issued within the last 6 months, and the previous year's marks card.", "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)).", "retrieved": "D07 p.1; D08 p.1; D07 p.1; D08 p.1; D04 p.1", "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]", "baseline_ok": true }, { "id": "M12", "category": "multi_passage", "question": "If a student qualifies for both the merit and need-based scholarships, what do they receive, and what is needed to renew it?", "expected_behaviour": "answer", "error_type": "incomplete answer (some key facts missing)", "decision": "answered", "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]", "expected_answer": "Only the higher-value scholarship; renewal needs a CGPA of at least 8.0 and no disciplinary action.", "explanation": "Answered: relevance 0.34, coverage 0.68, 3/3 sentences verified against their citations.", "retrieved": "D07 p.1; D07 p.2; D07 p.2; D05 p.1; D07 p.1", "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]", "baseline_ok": false }, { "id": "M16", "category": "multi_passage", "question": "Which MSc Data Science Semester 3 examination is held in the afternoon session, and what are the afternoon session timings?", "expected_behaviour": "answer", "error_type": "incomplete answer (some key facts missing)", "decision": "answered", "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]", "expected_answer": "MDS305 Security for Data Science on 10 December 2025; 2:00 PM to 5:00 PM.", "explanation": "Answered: relevance 0.50, coverage 0.62, 3/3 sentences verified against their citations.", "retrieved": "D06 p.1; D06 p.1; D06 p.2; D06 p.1; D13 p.2", "baseline_answer": "10 December 2025 (Wednesday): MDS305 Security for Data Science - Afternoon session. [2] MSc Data Science - Semester 3. [1]", "baseline_ok": false }, { "id": "M18", "category": "multi_passage", "question": "How many backlog courses prevent promotion to the next year, and when can backlogs be cleared through supplementary examinations?", "expected_behaviour": "answer", "error_type": "over-abstention (answer was available)", "decision": "abstained", "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "expected_answer": "More than 4 backlog courses; supplementary exams are held in June and July.", "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.", "retrieved": "D13 p.2; D03 p.2; D03 p.2; D11 p.2; D03 p.1", "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]", "baseline_ok": true }, { "id": "M19", "category": "multi_passage", "question": "How is participation in university-approved events treated for attendance, and who must approve it?", "expected_behaviour": "answer", "error_type": "over-abstention (answer was available)", "decision": "abstained", "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "expected_answer": "Counted as present for up to 10 contact hours per semester with prior approval of the Head of Department.", "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.", "retrieved": "D01 p.2; D04 p.1; D04 p.1; D01 p.1; D02 p.1", "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]", "baseline_ok": true }, { "id": "M20", "category": "multi_passage", "question": "A student returning from academic leave must re-register within which window, and what are the regular odd semester registration dates?", "expected_behaviour": "answer", "error_type": "wrong/irrelevant answer content", "decision": "answered", "answer": "Students returning from leave must re-register within the regular registration window. [1] Key Dates - Odd Semester 2025-26. [4]", "expected_answer": "Within the regular registration window: 1 July 2025 to 15 July 2025.", "explanation": "Answered: relevance 0.64, coverage 0.84, 2/2 sentences verified against their citations.", "retrieved": "D10 p.2; D10 p.2; D09 p.1; D14 p.1; D10 p.1", "baseline_answer": "Students returning from leave must re-register within the regular registration window. [1] Key Dates - Odd Semester 2025-26. [5]", "baseline_ok": false }, { "id": "N09", "category": "missing", "question": "What is the fee for a duplicate hall ticket?", "expected_behaviour": "abstain", "error_type": "answered unanswerable question (hallucination risk)", "decision": "answered", "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]", "expected_answer": "The documents do not contain this information; the system should abstain.", "explanation": "Answered: relevance 0.57, coverage 0.65, 2/2 sentences verified against their citations.", "retrieved": "D03 p.1; D06 p.2; D07 p.1; D01 p.1; D03 p.1; D05 p.1", "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]", "baseline_ok": false }, { "id": "N13", "category": "missing", "question": "What is the late fine for paying tuition fees after the due date?", "expected_behaviour": "abstain", "error_type": "answered unanswerable question (hallucination risk)", "decision": "answered", "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]", "expected_answer": "The documents do not contain this information; the system should abstain.", "explanation": "Answered: relevance 0.30, coverage 0.62, 3/3 sentences verified against their citations.", "retrieved": "D16 p.1; D04 p.2; D05 p.1; D10 p.2; D09 p.1; D05 p.1", "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]", "baseline_ok": false }, { "id": "N15", "category": "missing", "question": "What is the timetable for the even semester examinations in May 2026?", "expected_behaviour": "abstain", "error_type": "answered unanswerable question (hallucination risk)", "decision": "answered", "answer": "Even semester classes begin on 5 January 2026. [2] Only non-programmable scientific calculators are permitted in the examination hall. [1]", "expected_answer": "The documents do not contain this information; the system should abstain.", "explanation": "Answered: relevance 0.52, coverage 0.83, 2/2 sentences verified against their citations.", "retrieved": "D06 p.2; D14 p.2; D06 p.1; D06 p.1; D06 p.1; D14 p.1", "baseline_answer": "Even semester classes begin on 5 January 2026. [3] Only non-programmable scientific calculators are permitted in the examination hall. [1]", "baseline_ok": false }, { "id": "I05", "category": "misleading", "question": "Given that academic leave can be taken for up to four semesters, how early must a student apply?", "expected_behaviour": "correct_premise", "error_type": "over-abstention (answer was available)", "decision": "abstained", "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "expected_answer": "Academic leave is limited to two semesters; apply at least 30 days before the semester.", "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.", "retrieved": "D10 p.1; D10 p.2; D10 p.1; D10 p.1; D10 p.2", "baseline_answer": "A student may apply for academic leave (leave of absence) for a maximum of two semesters during the entire programme. [1]", "baseline_ok": false }, { "id": "I06", "category": "misleading", "question": "As the MDS301 Deep Learning exam is in the afternoon session, what time does it start?", "expected_behaviour": "correct_premise", "error_type": "wrong/irrelevant answer content", "decision": "answered", "answer": "01 December 2025 (Monday): MDS301 Deep Learning - Morning session. [1]", "expected_answer": "It is in the morning session (01 December 2025), which starts at 10:00 AM.", "explanation": "Answered: relevance 0.53, coverage 0.73, 1/1 sentences verified against their citations.", "retrieved": "D06 p.1; D06 p.1; D06 p.2; D06 p.1; D07 p.2", "baseline_answer": "01 December 2025 (Monday): MDS301 Deep Learning - Morning session. [1]", "baseline_ok": false }, { "id": "I13", "category": "misleading", "question": "What is the minimum CGPA for First Class (without distinction)?", "expected_behaviour": "answer", "error_type": "wrong/irrelevant answer content", "decision": "answered", "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]", "expected_answer": "6.5 (First Class is CGPA 6.5 to 7.99).", "explanation": "Answered: relevance 0.52, coverage 0.68, 2/2 sentences verified against their citations.", "retrieved": "D13 p.2; D13 p.2; D07 p.2; D03 p.1; D01 p.1", "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]", "baseline_ok": false }, { "id": "I15", "category": "misleading", "question": "Is a calculator with programmable memory allowed in the examination hall?", "expected_behaviour": "answer", "error_type": "over-abstention (answer was available)", "decision": "abstained", "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "expected_answer": "No - only non-programmable scientific calculators are permitted.", "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.", "retrieved": "D06 p.2; D03 p.1; D03 p.1; D06 p.1; D03 p.1", "baseline_answer": "Only non-programmable scientific calculators are permitted in the examination hall. [2]", "baseline_ok": true }, { "id": "C02", "category": "conflicting", "question": "Up to what percentage can an attendance shortage be condoned on medical grounds?", "expected_behaviour": "flag_conflict", "error_type": "over-abstention (answer was available)", "decision": "abstained", "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "expected_answer": "Conflict: 10% under the 2023 regulations; limited to 5% by the 2025 circular.", "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.", "retrieved": "D01 p.1; D01 p.1; D02 p.1; D02 p.1; D01 p.1", "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]", "baseline_ok": false }, { "id": "C04", "category": "conflicting", "question": "According to the examination eligibility rules, what attendance is needed in a course to sit its end-semester exam?", "expected_behaviour": "flag_conflict", "error_type": "missed conflict", "decision": "answered", "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]", "expected_answer": "Conflict: the eligibility rules (2024) state 75%, but the 2025 circular raises the requirement to 80%.", "explanation": "Answered: relevance 0.49, coverage 0.62, 2/2 sentences verified against their citations.", "retrieved": "D03 p.1; D03 p.1; D06 p.1; D03 p.2; D01 p.1", "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]", "baseline_ok": false }, { "id": "C16", "category": "conflicting", "question": "If my attendance in a course is 78%, am I eligible for the end-semester examination?", "expected_behaviour": "flag_conflict", "error_type": "missed conflict", "decision": "partial", "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]", "expected_answer": "Conflict: eligible under the 2023 rule (75%), but below the 80% minimum under the 2025 circular (condonable between 75% and 80%).", "explanation": "Partially answered: query coverage 0.56; not covered: 78%.", "retrieved": "D03 p.1; D01 p.1; D01 p.1; D03 p.1; D01 p.2; D03 p.2", "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]", "baseline_ok": false }, { "id": "C17", "category": "conflicting", "question": "If a PG student scores 45% in aggregate in a course, do they pass?", "expected_behaviour": "flag_conflict", "error_type": "over-abstention (answer was available)", "decision": "abstained", "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "expected_answer": "Conflict: pass under the Grading Policy (40%), fail under the PG Handbook (50%).", "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%.", "retrieved": "D15 p.1; D15 p.1; D13 p.1; D13 p.1; D09 p.1", "baseline_answer": "PG students must obtain at least 50% marks in aggregate to pass a course. [1]", "baseline_ok": false }, { "id": "C18", "category": "conflicting", "question": "What is the lowest attendance percentage that can be condoned on medical grounds?", "expected_behaviour": "flag_conflict", "error_type": "over-abstention (answer was available)", "decision": "abstained", "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "expected_answer": "Conflict: 65% under the 2023 regulations vs 75% under the 2025 circular.", "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.", "retrieved": "D01 p.1; D02 p.1; D02 p.1; D01 p.1; D01 p.1", "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]", "baseline_ok": false }, { "id": "C19", "category": "conflicting", "question": "Which attendance rule is the latest, and what minimum attendance does it require?", "expected_behaviour": "flag_conflict", "error_type": "over-abstention (answer was available)", "decision": "abstained", "answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "expected_answer": "Conflict: the 2025 circular (latest) requires 80%, superseding the 75% of the 2023 regulations.", "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.", "retrieved": "D01 p.1; D02 p.1; D01 p.1; D07 p.2; D09 p.1", "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]", "baseline_ok": false }, { "id": "C20", "category": "conflicting", "question": "According to the academic calendar, what is the scholarship application deadline, and has it changed?", "expected_behaviour": "flag_conflict", "error_type": "missed conflict", "decision": "answered", "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]", "expected_answer": "Conflict: the calendar says 31 August 2025, but the notice extends it to 15 September 2025.", "explanation": "Answered: relevance 0.31, coverage 0.64, 2/2 sentences verified against their citations.", "retrieved": "D14 p.1; D07 p.1; D05 p.1; D08 p.1; D08 p.1", "baseline_answer": "Last date for scholarship applications: 31 August 2025. [1]", "baseline_ok": false } ], "evidenceguard_fixes_over_baseline": [ { "id": "N01", "category": "missing", "question": "What is the fee for revaluation of answer scripts?", "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]", "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "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." }, { "id": "N02", "category": "missing", "question": "Who is the current Vice-Chancellor of Aranya Valley University?", "baseline_answer": "Students returning from leave must re-register within the regular registration window. [1]", "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "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." }, { "id": "N03", "category": "missing", "question": "What is the annual hostel fee for PhD students?", "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]", "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "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." }, { "id": "N04", "category": "missing", "question": "Does the university offer a sports quota scholarship?", "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]", "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "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." }, { "id": "N05", "category": "missing", "question": "What is the dress code during end-semester examinations?", "baseline_answer": "End-semester examinations: from 3 December 2025. [1]", "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "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." }, { "id": "N06", "category": "missing", "question": "Can students take the end-semester examinations online from home?", "baseline_answer": "The odd semester end-semester examinations commence on 1 December 2025 and conclude on 12 December 2025. [1]", "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "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." }, { "id": "N07", "category": "missing", "question": "What minimum CGPA is required to sit for campus placements?", "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]", "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "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." }, { "id": "N08", "category": "missing", "question": "How many total credits are required to graduate from the MSc Data Science programme?", "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]", "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "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." }, { "id": "N10", "category": "missing", "question": "On what date will the 2026 convocation ceremony be held?", "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]", "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "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." }, { "id": "N11", "category": "missing", "question": "What is the university policy on using generative AI tools such as ChatGPT in assignments?", "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]", "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "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." }, { "id": "N12", "category": "missing", "question": "What is the parking fee for students' two-wheelers on campus?", "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]", "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "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." }, { "id": "N14", "category": "missing", "question": "Does the university offer a tuition fee concession for siblings?", "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]", "evidenceguard_answer": "I could not find sufficient evidence in the uploaded documents to answer this question. Please check with the relevant university office.", "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." }, { "id": "C01", "category": "conflicting", "question": "What is the minimum attendance required to appear for end-semester examinations?", "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]", "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.", "explanation": "Answered with a conflict warning: 'Attendance Regulations 2023' and 'Circular: Amendment to Attendance Regulations' disagree (%: 75 vs 80 (context: attendance, minimum))." }, { "id": "C03", "category": "conflicting", "question": "What is the condonation fee per course for attendance shortage?", "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]", "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]", "explanation": "Answered with a conflict warning: 'Attendance Regulations 2023' and 'Circular: Amendment to Attendance Regulations' disagree (inr: 500 vs 1000 (context: condonation, fee))." }, { "id": "C05", "category": "conflicting", "question": "What is the last date to apply for a scholarship for 2025-26?", "baseline_answer": "The last date for scholarship applications for 2025-26 is extended to 15 September 2025. [1]", "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.", "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))." }, { "id": "C06", "category": "conflicting", "question": "What is the family income limit for the need-based scholarship?", "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]", "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]", "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))." }, { "id": "C07", "category": "conflicting", "question": "Are late assignment submissions accepted?", "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]", "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]", "explanation": "Answered with a conflict warning: 'Assignment Submission Policy 2024' and 'Internal Assessment Guidelines 2024' disagree (one passage permits what the other rules out)." }, { "id": "C08", "category": "conflicting", "question": "What is the penalty for submitting an assignment one day late?", "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]", "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]", "explanation": "Answered with a conflict warning: 'Assignment Submission Policy 2024' and 'Internal Assessment Guidelines 2024' disagree (one passage permits what the other rules out)." }, { "id": "C09", "category": "conflicting", "question": "How many books can a postgraduate student borrow from the library?", "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]", "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]", "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))." }, { "id": "C10", "category": "conflicting", "question": "For how many days can a postgraduate student keep a borrowed library book?", "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]", "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]", "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))." }, { "id": "C11", "category": "conflicting", "question": "What is the library overdue fine per book per day?", "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]", "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]", "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))." }, { "id": "C12", "category": "conflicting", "question": "How long is the add/drop period for elective courses?", "baseline_answer": "Add/drop period for electives: 7 working days from the start of classes. [2]", "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.", "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))." }, { "id": "C13", "category": "conflicting", "question": "What minimum aggregate percentage is needed to pass a postgraduate course?", "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]", "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]", "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))." }, { "id": "C14", "category": "conflicting", "question": "On what date do the odd semester end-semester examinations begin?", "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]", "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]", "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))." }, { "id": "C15", "category": "conflicting", "question": "Can I drop an elective course 9 working days after classes start?", "baseline_answer": "Students may add or drop elective courses within 10 working days from the start of classes. [1]", "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.", "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))." } ]}12345678910111213split,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
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
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
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
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
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
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
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
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
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
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
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
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.0037123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537{ "meta": { "note": "Experiments use SYNTHETIC documents of a fictional university. Results do not establish real-world university policy accuracy.", "components": { "Embeddings": "LSA (TF-IDF + TruncatedSVD) - offline fallback", "Vector store": "FAISS IndexFlatIP (cosine)", "Keyword retrieval": "BM25 (rank_bm25) fused with Reciprocal Rank Fusion", "Reranker": "Lexical cross-scorer (IDF coverage + bigrams + BM25) - offline fallback", "Evidence verifier": "Rule-based verifier (numeric mismatch, polarity flip, lexical support) - offline fallback", "Generator": "Extractive composer (no LLM) - offline fallback" }, "backend": "lite", "llm_backend": "extractive", "thresholds": { "min_relevance": 0.15, "min_coverage": 0.6, "partial_coverage": 0.5, "min_confidence": 0.3, "conflict_topic_sim": 0.3, "conflict_sentence_coverage": 0.35, "conflict_min_shared": 2, "conflict_subject_mismatch": 0.3, "conflict_min_relevance": 0.25, "nli_contradiction": 0.6, "nli_entailment": 0.5, "citation_overlap": 0.5 }, "n_questions": 100, "dev_questions": 29, "test_questions": 71, "python": "3.13.18", "machine": "x86_64", "cpu_count": 2, "runtime_s": 23.7, "date": "2026-11-19 07:51" }, "metrics": { "all": { "baseline": { "n_questions": 100, "precision_at_k": 0.4541, "recall_at_k": 0.9647, "mrr": 0.9765, "answer_correctness": 0.57, "faithfulness": 1.0, "grounded_faithfulness": 0.7567, "answer_relevance": 0.4425, "context_precision": 0.9244, "context_recall": 0.9765, "unsupported_answer_rate": 0.19, "abstention_accuracy": 0.85, "abstention_precision": 0.0, "abstention_recall": 0.0, "abstention_f1": 0.0, "abstention_rate": 0.0, "contradiction_precision": 0.0, "contradiction_recall": 0.0, "contradiction_f1": 0.0, "contradiction_accuracy": 0.8, "citation_support_accuracy": 0.7483, "behaviour_accuracy": 0.55, "avg_response_time_s": 0.0014, "avg_retrieval_time_s": 0.0006, "avg_generation_time_s": 0.0007, "avg_verification_time_s": 0.0 }, "rerank": { "n_questions": 100, "precision_at_k": 0.44, "recall_at_k": 0.9765, "mrr": 0.9588, "answer_correctness": 0.56, "faithfulness": 1.0, "grounded_faithfulness": 0.735, "answer_relevance": 0.4417, "context_precision": 0.9101, "context_recall": 0.9824, "unsupported_answer_rate": 0.2, "abstention_accuracy": 0.85, "abstention_precision": 0.0, "abstention_recall": 0.0, "abstention_f1": 0.0, "abstention_rate": 0.0, "contradiction_precision": 0.0, "contradiction_recall": 0.0, "contradiction_f1": 0.0, "contradiction_accuracy": 0.8, "citation_support_accuracy": 0.72, "behaviour_accuracy": 0.54, "avg_response_time_s": 0.0023, "avg_retrieval_time_s": 0.0017, "avg_generation_time_s": 0.0006, "avg_verification_time_s": 0.0 }, "verify": { "n_questions": 100, "precision_at_k": 0.4148, "recall_at_k": 0.9765, "mrr": 0.9765, "answer_correctness": 0.73, "faithfulness": 1.0, "grounded_faithfulness": 0.8311, "answer_relevance": 0.473, "context_precision": 0.921, "context_recall": 0.9824, "unsupported_answer_rate": 0.09, "abstention_accuracy": 0.83, "abstention_precision": 0.4615, "abstention_recall": 0.8, "abstention_f1": 0.5854, "abstention_rate": 0.26, "contradiction_precision": 0.8667, "contradiction_recall": 0.65, "contradiction_f1": 0.7429, "contradiction_accuracy": 0.91, "citation_support_accuracy": 0.8108, "behaviour_accuracy": 0.73, "avg_response_time_s": 0.0042, "avg_retrieval_time_s": 0.001, "avg_generation_time_s": 0.0005, "avg_verification_time_s": 0.0027 }, "full": { "n_questions": 100, "precision_at_k": 0.4106, "recall_at_k": 0.9824, "mrr": 0.9588, "answer_correctness": 0.73, "faithfulness": 1.0, "grounded_faithfulness": 0.8221, "answer_relevance": 0.4744, "context_precision": 0.9059, "context_recall": 0.9882, "unsupported_answer_rate": 0.09, "abstention_accuracy": 0.83, "abstention_precision": 0.4615, "abstention_recall": 0.8, "abstention_f1": 0.5854, "abstention_rate": 0.26, "contradiction_precision": 0.8667, "contradiction_recall": 0.65, "contradiction_f1": 0.7429, "contradiction_accuracy": 0.91, "citation_support_accuracy": 0.8018, "behaviour_accuracy": 0.73, "avg_response_time_s": 0.0055, "avg_retrieval_time_s": 0.0018, "avg_generation_time_s": 0.0005, "avg_verification_time_s": 0.0031 } }, "test": { "baseline": { "n_questions": 71, "precision_at_k": 0.4633, "recall_at_k": 0.975, "mrr": 0.975, "answer_correctness": 0.5634, "faithfulness": 1.0, "grounded_faithfulness": 0.77, "answer_relevance": 0.4523, "context_precision": 0.9279, "context_recall": 0.9833, "unsupported_answer_rate": 0.2113, "abstention_accuracy": 0.8451, "abstention_precision": 0.0, "abstention_recall": 0.0, "abstention_f1": 0.0, "abstention_rate": 0.0, "contradiction_precision": 0.0, "contradiction_recall": 0.0, "contradiction_f1": 0.0, "contradiction_accuracy": 0.8028, "citation_support_accuracy": 0.7559, "behaviour_accuracy": 0.5352, "avg_response_time_s": 0.0014, "avg_retrieval_time_s": 0.0006, "avg_generation_time_s": 0.0007, "avg_verification_time_s": 0.0 }, "rerank": { "n_questions": 71, "precision_at_k": 0.46, "recall_at_k": 0.9917, "mrr": 0.9583, "answer_correctness": 0.5493, "faithfulness": 1.0, "grounded_faithfulness": 0.7465, "answer_relevance": 0.4496, "context_precision": 0.9154, "context_recall": 0.9917, "unsupported_answer_rate": 0.2254, "abstention_accuracy": 0.8451, "abstention_precision": 0.0, "abstention_recall": 0.0, "abstention_f1": 0.0, "abstention_rate": 0.0, "contradiction_precision": 0.0, "contradiction_recall": 0.0, "contradiction_f1": 0.0, "contradiction_accuracy": 0.8028, "citation_support_accuracy": 0.73, "behaviour_accuracy": 0.5211, "avg_response_time_s": 0.0023, "avg_retrieval_time_s": 0.0017, "avg_generation_time_s": 0.0006, "avg_verification_time_s": 0.0 }, "verify": { "n_questions": 71, "precision_at_k": 0.4305, "recall_at_k": 0.9833, "mrr": 0.975, "answer_correctness": 0.7042, "faithfulness": 1.0, "grounded_faithfulness": 0.8576, "answer_relevance": 0.5024, "context_precision": 0.9237, "context_recall": 0.9833, "unsupported_answer_rate": 0.0986, "abstention_accuracy": 0.8028, "abstention_precision": 0.4348, "abstention_recall": 0.9091, "abstention_f1": 0.5882, "abstention_rate": 0.3239, "contradiction_precision": 0.8182, "contradiction_recall": 0.6429, "contradiction_f1": 0.72, "contradiction_accuracy": 0.9014, "citation_support_accuracy": 0.8264, "behaviour_accuracy": 0.7042, "avg_response_time_s": 0.004, "avg_retrieval_time_s": 0.001, "avg_generation_time_s": 0.0005, "avg_verification_time_s": 0.0026 }, "full": { "n_questions": 71, "precision_at_k": 0.4347, "recall_at_k": 0.9917, "mrr": 0.9583, "answer_correctness": 0.7042, "faithfulness": 1.0, "grounded_faithfulness": 0.8438, "answer_relevance": 0.5018, "context_precision": 0.915, "context_recall": 0.9917, "unsupported_answer_rate": 0.0986, "abstention_accuracy": 0.8028, "abstention_precision": 0.4348, "abstention_recall": 0.9091, "abstention_f1": 0.5882, "abstention_rate": 0.3239, "contradiction_precision": 0.8182, "contradiction_recall": 0.6429, "contradiction_f1": 0.72, "contradiction_accuracy": 0.9014, "citation_support_accuracy": 0.8125, "behaviour_accuracy": 0.7042, "avg_response_time_s": 0.0052, "avg_retrieval_time_s": 0.0018, "avg_generation_time_s": 0.0005, "avg_verification_time_s": 0.0029 } }, "dev": { "baseline": { "n_questions": 29, "precision_at_k": 0.432, "recall_at_k": 0.94, "mrr": 0.98, "answer_correctness": 0.5862, "faithfulness": 1.0, "grounded_faithfulness": 0.7241, "answer_relevance": 0.4185, "context_precision": 0.9159, "context_recall": 0.96, "unsupported_answer_rate": 0.1379, "abstention_accuracy": 0.8621, "abstention_precision": 0.0, "abstention_recall": 0.0, "abstention_f1": 0.0, "abstention_rate": 0.0, "contradiction_precision": 0.0, "contradiction_recall": 0.0, "contradiction_f1": 0.0, "contradiction_accuracy": 0.7931, "citation_support_accuracy": 0.7299, "behaviour_accuracy": 0.5862, "avg_response_time_s": 0.0013, "avg_retrieval_time_s": 0.0006, "avg_generation_time_s": 0.0007, "avg_verification_time_s": 0.0 }, "rerank": { "n_questions": 29, "precision_at_k": 0.392, "recall_at_k": 0.94, "mrr": 0.96, "answer_correctness": 0.5862, "faithfulness": 1.0, "grounded_faithfulness": 0.7069, "answer_relevance": 0.4222, "context_precision": 0.8973, "context_recall": 0.96, "unsupported_answer_rate": 0.1379, "abstention_accuracy": 0.8621, "abstention_precision": 0.0, "abstention_recall": 0.0, "abstention_f1": 0.0, "abstention_rate": 0.0, "contradiction_precision": 0.0, "contradiction_recall": 0.0, "contradiction_f1": 0.0, "contradiction_accuracy": 0.7931, "citation_support_accuracy": 0.6954, "behaviour_accuracy": 0.5862, "avg_response_time_s": 0.0023, "avg_retrieval_time_s": 0.0016, "avg_generation_time_s": 0.0006, "avg_verification_time_s": 0.0 }, "verify": { "n_questions": 29, "precision_at_k": 0.3772, "recall_at_k": 0.96, "mrr": 0.98, "answer_correctness": 0.7931, "faithfulness": 1.0, "grounded_faithfulness": 0.7821, "answer_relevance": 0.4189, "context_precision": 0.9146, "context_recall": 0.98, "unsupported_answer_rate": 0.069, "abstention_accuracy": 0.8966, "abstention_precision": 0.6667, "abstention_recall": 0.5, "abstention_f1": 0.5714, "abstention_rate": 0.1034, "contradiction_precision": 1.0, "contradiction_recall": 0.6667, "contradiction_f1": 0.8, "contradiction_accuracy": 0.931, "citation_support_accuracy": 0.7821, "behaviour_accuracy": 0.7931, "avg_response_time_s": 0.0048, "avg_retrieval_time_s": 0.0009, "avg_generation_time_s": 0.0007, "avg_verification_time_s": 0.0031 }, "full": { "n_questions": 29, "precision_at_k": 0.3527, "recall_at_k": 0.96, "mrr": 0.96, "answer_correctness": 0.7931, "faithfulness": 1.0, "grounded_faithfulness": 0.7821, "answer_relevance": 0.4238, "context_precision": 0.8839, "context_recall": 0.98, "unsupported_answer_rate": 0.069, "abstention_accuracy": 0.8966, "abstention_precision": 0.6667, "abstention_recall": 0.5, "abstention_f1": 0.5714, "abstention_rate": 0.1034, "contradiction_precision": 1.0, "contradiction_recall": 0.6667, "contradiction_f1": 0.8, "contradiction_accuracy": 0.931, "citation_support_accuracy": 0.7821, "behaviour_accuracy": 0.7931, "avg_response_time_s": 0.0061, "avg_retrieval_time_s": 0.0017, "avg_generation_time_s": 0.0007, "avg_verification_time_s": 0.0037 } } }, "by_category": { "baseline": { "answerable": { "n": 30, "answer_correctness": 1.0, "behaviour_accuracy": 1.0, "unsupported_rate": 0.0, "abstention_rate": 0.0 }, "conflicting": { "n": 20, "answer_correctness": 0.1, "behaviour_accuracy": 0.0, "unsupported_rate": 0.05, "abstention_rate": 0.0 }, "misleading": { "n": 15, "answer_correctness": 0.8, "behaviour_accuracy": 0.8, "unsupported_rate": 0.1333, "abstention_rate": 0.0 }, "missing": { "n": 15, "answer_correctness": 0.0, "behaviour_accuracy": 0.0, "unsupported_rate": 1.0, "abstention_rate": 0.0 }, "multi_passage": { "n": 20, "answer_correctness": 0.65, "behaviour_accuracy": 0.65, "unsupported_rate": 0.05, "abstention_rate": 0.0 } }, "rerank": { "answerable": { "n": 30, "answer_correctness": 1.0, "behaviour_accuracy": 1.0, "unsupported_rate": 0.0, "abstention_rate": 0.0 }, "conflicting": { "n": 20, "answer_correctness": 0.1, "behaviour_accuracy": 0.0, "unsupported_rate": 0.05, "abstention_rate": 0.0 }, "misleading": { "n": 15, "answer_correctness": 0.8, "behaviour_accuracy": 0.8, "unsupported_rate": 0.1333, "abstention_rate": 0.0 }, "missing": { "n": 15, "answer_correctness": 0.0, "behaviour_accuracy": 0.0, "unsupported_rate": 1.0, "abstention_rate": 0.0 }, "multi_passage": { "n": 20, "answer_correctness": 0.6, "behaviour_accuracy": 0.6, "unsupported_rate": 0.1, "abstention_rate": 0.0 } }, "verify": { "answerable": { "n": 30, "answer_correctness": 0.9, "behaviour_accuracy": 0.9, "unsupported_rate": 0.0, "abstention_rate": 0.1 }, "conflicting": { "n": 20, "answer_correctness": 0.65, "behaviour_accuracy": 0.65, "unsupported_rate": 0.05, "abstention_rate": 0.2 }, "misleading": { "n": 15, "answer_correctness": 0.7333, "behaviour_accuracy": 0.7333, "unsupported_rate": 0.1333, "abstention_rate": 0.1333 }, "missing": { "n": 15, "answer_correctness": 0.8, "behaviour_accuracy": 0.8, "unsupported_rate": 0.2, "abstention_rate": 0.8 }, "multi_passage": { "n": 20, "answer_correctness": 0.5, "behaviour_accuracy": 0.5, "unsupported_rate": 0.15, "abstention_rate": 0.25 } }, "full": { "answerable": { "n": 30, "answer_correctness": 0.9, "behaviour_accuracy": 0.9, "unsupported_rate": 0.0, "abstention_rate": 0.1 }, "conflicting": { "n": 20, "answer_correctness": 0.65, "behaviour_accuracy": 0.65, "unsupported_rate": 0.05, "abstention_rate": 0.2 }, "misleading": { "n": 15, "answer_correctness": 0.7333, "behaviour_accuracy": 0.7333, "unsupported_rate": 0.1333, "abstention_rate": 0.1333 }, "missing": { "n": 15, "answer_correctness": 0.8, "behaviour_accuracy": 0.8, "unsupported_rate": 0.2, "abstention_rate": 0.8 }, "multi_passage": { "n": 20, "answer_correctness": 0.5, "behaviour_accuracy": 0.5, "unsupported_rate": 0.15, "abstention_rate": 0.25 } } }, "config_names": { "baseline": "Baseline RAG", "rerank": "+ Reranking", "verify": "+ Verification", "full": "EvidenceGuard" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158{ "behaviour_accuracy|all|baseline_vs_rerank": { "n": 100, "baseline": 0.55, "rerank": 0.54, "difference": -0.01, "ci95": [ -0.03, 0.0 ], "only_other_true": 0, "only_baseline_true": 1, "mcnemar_exact_p": 1.0 }, "behaviour_accuracy|all|baseline_vs_verify": { "n": 100, "baseline": 0.55, "verify": 0.73, "difference": 0.18, "ci95": [ 0.08, 0.28 ], "only_other_true": 25, "only_baseline_true": 7, "mcnemar_exact_p": 0.002102 }, "behaviour_accuracy|all|baseline_vs_full": { "n": 100, "baseline": 0.55, "full": 0.73, "difference": 0.18, "ci95": [ 0.08, 0.28 ], "only_other_true": 25, "only_baseline_true": 7, "mcnemar_exact_p": 0.002102 }, "behaviour_accuracy|test|baseline_vs_rerank": { "n": 71, "baseline": 0.5352, "rerank": 0.5211, "difference": -0.0141, "ci95": [ -0.0423, 0.0 ], "only_other_true": 0, "only_baseline_true": 1, "mcnemar_exact_p": 1.0 }, "behaviour_accuracy|test|baseline_vs_verify": { "n": 71, "baseline": 0.5352, "verify": 0.7042, "difference": 0.169, "ci95": [ 0.0423, 0.2958 ], "only_other_true": 19, "only_baseline_true": 7, "mcnemar_exact_p": 0.028959 }, "behaviour_accuracy|test|baseline_vs_full": { "n": 71, "baseline": 0.5352, "full": 0.7042, "difference": 0.169, "ci95": [ 0.0423, 0.2958 ], "only_other_true": 19, "only_baseline_true": 7, "mcnemar_exact_p": 0.028959 }, "unsupported_answer|all|baseline_vs_rerank": { "n": 100, "baseline": 0.19, "rerank": 0.2, "difference": 0.01, "ci95": [ 0.0, 0.03 ], "only_other_true": 1, "only_baseline_true": 0, "mcnemar_exact_p": 1.0 }, "unsupported_answer|all|baseline_vs_verify": { "n": 100, "baseline": 0.19, "verify": 0.09, "difference": -0.1, "ci95": [ -0.17, -0.03 ], "only_other_true": 2, "only_baseline_true": 12, "mcnemar_exact_p": 0.012939 }, "unsupported_answer|all|baseline_vs_full": { "n": 100, "baseline": 0.19, "full": 0.09, "difference": -0.1, "ci95": [ -0.17, -0.03 ], "only_other_true": 2, "only_baseline_true": 12, "mcnemar_exact_p": 0.012939 }, "unsupported_answer|test|baseline_vs_rerank": { "n": 71, "baseline": 0.2113, "rerank": 0.2254, "difference": 0.0141, "ci95": [ 0.0, 0.0423 ], "only_other_true": 1, "only_baseline_true": 0, "mcnemar_exact_p": 1.0 }, "unsupported_answer|test|baseline_vs_verify": { "n": 71, "baseline": 0.2113, "verify": 0.0986, "difference": -0.1127, "ci95": [ -0.2113, -0.0282 ], "only_other_true": 2, "only_baseline_true": 10, "mcnemar_exact_p": 0.038574 }, "unsupported_answer|test|baseline_vs_full": { "n": 71, "baseline": 0.2113, "full": 0.0986, "difference": -0.1127, "ci95": [ -0.2113, -0.0282 ], "only_other_true": 2, "only_baseline_true": 10, "mcnemar_exact_p": 0.038574 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492"""Builds the MSc project report content (reports/report_model.json) from the ACTUAL result files,then renders DOCX (scripts/render_report_docx.js) and PDF (LibreOffice). Also refreshes the resultstable in README.md. No number in the report is typed by hand - all are read from results/.
Usage: python scripts/build_report.py [--author "Name"] [--usn USN]"""import argparseimport jsonimport subprocessimport sysfrom collections import Counterfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT))sys.path.insert(0, str(ROOT / "scripts"))
from corpus_content import DOCUMENTS # noqa: E402from src.research import FOUNDATION, FUTURE, LIMITATIONS, OBJECTIVES, PAPERS, RESEARCH_GAP # noqa: E402
RES = ROOT / "results"M = json.loads((RES / "metrics.json").read_text())SIG = json.loads((RES / "significance.json").read_text())CAL = json.loads((RES / "calibrated_thresholds.json").read_text())FAIL = json.loads((RES / "failure_cases.json").read_text())QS = json.loads((ROOT / "evaluation_data" / "questions.json").read_text())ORDER = ["baseline", "rerank", "verify", "full"]NAMES = M["config_names"]B = [] # blocks
def H1(t): B.append({"t": "h1", "text": t})def H2(t): B.append({"t": "h2", "text": t})def P(t): B.append({"t": "p", "text": t})def BUL(items): B.append({"t": "bullets", "items": list(items)})def NUM(items): B.append({"t": "numbers", "items": list(items)})def TABLE(header, rows, widths=None, size=8): B.append({"t": "table", "header": header, "rows": rows, "widths": widths, "size": size})def IMG(path, w=16, cap=""): B.append({"t": "img", "path": str(path), "width_cm": w, "caption": cap})def CAP(t): B.append({"t": "caption", "text": t})def BR(): B.append({"t": "pagebreak"})def CODE(t): B.append({"t": "code", "text": t})
def plain(t): """Strip the app's markdown (bold/italic markers, list dashes, emoji badges) for report tables.""" import re t = re.sub(r"\*{1,2}|(?<!\w)_(?!\w)", "", t.replace("\n", " ")) return re.sub(r"\s+-\s+", " | ", t.replace("⚠️", "[!]")).strip()
def f(x, d=3): return "-" if x is None else f"{x:.{d}f}"
def m(split, cfg, key): return M["metrics"][split][cfg][key]
def build(author, usn, programme, institution): meta = M["meta"] A, T = "all", "test" sig_b = SIG["behaviour_accuracy|test|baseline_vs_full"] sig_u = SIG["unsupported_answer|test|baseline_vs_full"] sig_ba = SIG["behaviour_accuracy|all|baseline_vs_full"]
# --------------------------------------------------------------- title page B.append({"t": "title", "title": "EvidenceGuard AI", "subtitle": "A Reliable University Knowledge Assistant Using Retrieval-Augmented Generation, " "Large Language Models and Evidence Verification", "lines": ["MSc Project Report - Generative AI and Large Language Models", f"Submitted by: {author}" + (f" (USN: {usn})" if usn else ""), programme, institution, "Guide: ______________________", "November 2026"]}) BR()
# --------------------------------------------------------------- abstract H1("Abstract") P("Standard retrieval-augmented generation (RAG) assistants answer every question, even when the retrieved " "documents do not contain the answer or contain contradictory versions of the same rule. For students asking " "about attendance, examination eligibility or scholarship deadlines, a fluent but unsupported answer is a " "real risk. This project builds EvidenceGuard AI, a university knowledge assistant that verifies evidence " "before answering. It combines hybrid retrieval (FAISS dense vectors fused with BM25 by reciprocal rank " "fusion), cross-encoder reranking, an evidence-sufficiency check, a conflict-search retrieval step with " "numeric-aware contradiction detection, context-grounded generation, sentence-level citation validation and " "confidence-based abstention with natural-language explanations. Because no data was available, a corpus of " f"{len(DOCUMENTS)} explicitly fictional university PDFs (28 pages) and a 100-question benchmark with " "labelled answerable, multi-passage, missing-information, misleading and conflicting questions were " "generated from a single fact base. A four-configuration ablation was run on CPU with offline fallback " "components (Hugging Face downloads were unavailable in the build environment). On the 71 held-out test " f"questions, EvidenceGuard raised expected-behaviour accuracy from {m(T,'baseline','behaviour_accuracy'):.1%} " f"to {m(T,'full','behaviour_accuracy'):.1%} (exact McNemar p = {sig_b['mcnemar_exact_p']:.3f}) and reduced the " f"unsupported-answer rate from {m(T,'baseline','unsupported_answer_rate'):.1%} to " f"{m(T,'full','unsupported_answer_rate'):.1%} (p = {sig_u['mcnemar_exact_p']:.3f}), detecting conflicting " f"evidence with F1 = {m(T,'full','contradiction_f1'):.2f}. The gains come from the verification layer; " "reranking alone gave no improvement, and verification costs some over-abstention on answerable " "multi-part questions. All results use synthetic data and do not establish accuracy on real university " "policies. The system is delivered as a seven-tab Gradio application prepared for Hugging Face Spaces.") P("Keywords: retrieval-augmented generation, hallucination, abstention, contradiction detection, citation " "verification, natural language inference, FAISS, Gradio.") BR()
# --------------------------------------------------------------- 1-3 H1("1. Introduction") P("Large language models (LLMs) generate fluent text but can hallucinate. Retrieval-augmented generation " "[9] reduces this by conditioning the model on retrieved passages, and it has become the default design for " "institutional chatbots. Universities are a natural application: rules on attendance, assessment, " "scholarships and libraries are spread across regulations, amendment circulars, notices and handbooks that " "change every year. Students frequently ask questions whose answers are missing from the documents, are " "split across documents, or have been changed by a newer circular.") P("Recent benchmarks show that LLMs inside RAG pipelines struggle exactly here: they rarely refuse when " "evidence is missing, integrate several documents poorly and are misled by false or conflicting context [1], " "[6], and they still produce claims unsupported by the retrieved text [8]. This project designs, implements " "and evaluates a verification layer that addresses these failure modes with free, CPU-friendly components.")
H1("2. Problem Statement") P("Ordinary LLM systems may generate unsupported answers, hallucinate information or fail to recognise " "conflicting documents. The task is to build a university knowledge assistant that retrieves information " "from uploaded documents and verifies whether sufficient and consistent evidence exists before generating " "an answer, and to measure, against a standard RAG baseline, whether this verification reduces unsupported " "answers without unacceptable loss of helpfulness.")
H1("3. Research Objectives") NUM(OBJECTIVES) P("Research questions. RQ1: Does evidence verification reduce unsupported answers compared with standard RAG? " "RQ2: Can inter-document conflicts in versioned university rules be detected with training-free components? " "RQ3: What is the cost of verification in over-abstention and latency? RQ4: How much do hybrid retrieval and " "reranking contribute on their own?") BR()
# --------------------------------------------------------------- 4 literature H1("4. Literature Review") P("Papers were identified through targeted searches of AAAI, ICLR, NeurIPS, ACL Anthology and arXiv, and " "every bibliographic detail below was verified against the publisher or proceedings page. Eight papers " "from 2023-2024 were selected because each addresses one failure mode that EvidenceGuard targets.") for i, p in enumerate(PAPERS, 1): H2(f"4.{i} {p['title']} ({p['authors'].split(',')[0].split()[-1]} et al., {p['year']})") P(f"{p['venue']}. Problem: {p['problem']} Method: {p['method']} Technologies: {p['technologies']} " f"Results: {p['results']} Limitations: {p['limitations']}") H2("4.9 Literature review table") rows = [[f"[{i}] {p['title']} - {p['authors']} ({p['year']}), {p['venue']}", p["problem"] + " / " + p["method"], p["results"], p["limitations"], p["gap"], p["ours"]] for i, p in enumerate(PAPERS, 1)] TABLE(["Paper", "Problem / methodology", "Results", "Limitations", "Research gap", "How EvidenceGuard addresses it"], rows, widths=[2.6, 3.0, 2.4, 2.4, 2.2, 3.0], size=7) CAP("Table 1. Literature review (technologies are listed in Sections 4.1-4.8).") BR()
H1("5. Research Gap") P(RESEARCH_GAP) P("Why this gap is realistic for a student project: all components are pre-trained and free (no fine-tuning), " "the corpus and benchmark are generated locally, and the full experiment runs on a laptop CPU.")
# --------------------------------------------------------------- 6 methodology H1("6. Proposed Methodology") NUM(["Data creation: generate a fictional but internally consistent policy corpus with planted conflicts, " "superseding circulars, distractors and uncovered topics; derive 100 questions with gold evidence pages.", "Baseline (System A): PDF ingestion, cleaning, sentence-aware chunking, Sentence-Transformer embeddings, " "FAISS search, LLM generation with source citations.", "EvidenceGuard (System B): hybrid retrieval, cross-encoder reranking, sufficiency gate, conflict-search " "retrieval and contradiction detection, conflict-aware grounded generation, citation validation, " "confidence-based abstention and explanation.", f"Calibration: thresholds tuned by grid search on a stratified DEV split ({meta['dev_questions']} " f"questions) only; results reported on all 100 and on the {meta['test_questions']} held-out TEST questions.", "Ablation: (1) baseline, (2) + hybrid retrieval and reranking, (3) + verification without reranking, " "(4) complete EvidenceGuard; paired significance tests (exact McNemar, bootstrap 95% CI)."])
H1("7. System Architecture") IMG(ROOT / "assets" / "architecture.png", 16.5) CAP("Figure 1. EvidenceGuard AI architecture (ingestion layer, System A, System B and user interface).") P("The code is modular (src/): document_processor (extraction, cleaning, chunking), embeddings, vector_store " "(FAISS + BM25 knowledge base), retrieval (dense, BM25, hybrid RRF), reranker, evidence_verifier, " "llm_generator, baseline_rag, enhanced_rag, evaluation and system (factory). Every Hugging Face component " "has an offline fallback selected automatically if the model cannot be loaded.")
H1("8. Workflow Diagram") IMG(ROOT / "assets" / "workflow.png", 12.5) CAP("Figure 2. Decision workflow of EvidenceGuard: answered, partial, conflict warning or abstained.") BR()
# --------------------------------------------------------------- 9 dataset H1("9. Dataset Creation Methodology") P("No external data was used. The script scripts/generate_dataset.py renders every document from a single " "Python fact base (scripts/corpus_content.py) with ReportLab, so facts are consistent by construction. " "Each page carries the banner 'SYNTHETIC DEMONSTRATION DATA - fictional university, not a real policy', a " "metadata table (document number, version, issue and effective dates) and page numbers.") TABLE(["ID", "Document", "Issued", "Pages", "Role in the benchmark"], [[d["id"], d["title"], d["issued"], str(len(d["pages"])), d["topic"]] for d in DOCUMENTS], widths=[1.0, 7.0, 2.2, 1.2, 4.6], size=7.5) CAP("Table 2. Synthetic document collection (Aranya Valley University is fictional).") P("Planted conflicts: minimum attendance 75% vs 80%; condonation limit 10% vs 5% and fee INR 500 vs INR 1,000; " "scholarship deadline 31 August vs 15 September 2025 and income ceiling INR 6,00,000 vs 8,00,000; late " "assignments accepted with a 10%/day penalty vs not accepted; PG borrowing 5 books/14 days/INR 5 fine vs " "6 books/21 days/INR 10; add/drop 10 vs 7 working days; PG pass mark 40% vs 50%; examinations starting " "1 vs 3 December 2025. A hostel guidelines document acts as a distractor full of look-alike numbers.") cats = Counter(q["category"] for q in QS) TABLE(["Category", "Questions", "Expected evidence status", "Expected behaviour"], [["Answerable", str(cats["answerable"]), "sufficient", "answer with citation"], ["Multi-passage", str(cats["multi_passage"]), "sufficient", "combine two passages / documents"], ["Missing information", str(cats["missing"]), "insufficient", "abstain"], ["Misleading / irrelevant context", str(cats["misleading"]), "sufficient", "correct a false premise or ignore distractors"], ["Conflicting", str(cats["conflicting"]), "conflicting", "flag the conflict and present both versions"]], widths=[4.0, 2.0, 3.6, 6.4], size=8) CAP("Table 3. Evaluation question set (evaluation_data/questions.json and .csv).") P("Each question stores the expected answer, the key facts a correct answer must contain, the supporting " "document(s) and page(s), the expected evidence status and the expected behaviour. The generator locates " "every evidence phrase in the extracted PDF text and refuses to write the dataset if a phrase or key fact " "is missing, which guarantees that questions are derived from the PDFs.")
# --------------------------------------------------------------- 10 models H1("10. Model Selection") TABLE(["Role", "Hugging Face model (deployment)", "Why", "Offline fallback (used in reported run)"], [["Embeddings", "sentence-transformers/all-MiniLM-L6-v2 (384-d)", "Small, fast on CPU, strong general retrieval [10]", "LSA: TF-IDF (1-2 grams) + TruncatedSVD"], ["Vector DB", "FAISS IndexFlatIP", "Exact cosine search; corpus is small [11]", "same"], ["Keyword", "BM25 (rank_bm25) + RRF", "Exact terms such as 'condonation', codes, dates [12], [13]", "same"], ["Reranker", "cross-encoder/ms-marco-MiniLM-L-6-v2", "Joint query-passage scoring [14]", "Lexical cross-scorer (IDF coverage, bigrams, BM25)"], ["NLI", "cross-encoder/nli-deberta-v3-xsmall", "Contradiction/entailment probabilities; ~70M params", "Numeric-value and polarity rules"], ["LLM", "Qwen/Qwen2.5-0.5B-Instruct (local CPU) or HF Inference API (HF_TOKEN secret)", "Free, instruction-tuned, fits free CPU Space", "Extractive composer (no LLM)"]], widths=[2.0, 4.6, 4.6, 4.8], size=7.5) CAP("Table 4. Model selection. The model licences should be re-checked on each model card before deployment.") P("Constraints considered: free CPU Spaces (2 vCPU, 16 GB RAM) make 7B models impractical locally, so the " "default local LLM is a 0.5B model and a larger model can be used through the Hugging Face Inference API " "with a token stored as a Space secret. No API key is written in code. NLI models are known to be weak at " "comparing numbers, which dominate policy text, so contradiction detection always also runs explicit " "numeric-value rules.") BR()
# --------------------------------------------------------------- 11 implementation H1("11. Implementation") H2("11.1 Ingestion and indexing") P("PyMuPDF extracts page text (pypdf fallback). Cleaning removes the synthetic-data banner and footers, " "de-hyphenates, and terminates short title-case headings so they do not merge with the next sentence. " "Pages are split into sentences and packed into ~70-word chunks with a one-sentence overlap; each chunk keeps " "its document, title, page and issue date. The knowledge base builds a FAISS index and a BM25 index and " "stores IDF weights used by the verifier. Uploaded PDFs are added (or replaced) at run time.") H2("11.2 Evidence sufficiency") P("The verifier extracts content words of the question (stop words and generic domain words removed, light " "stemming) and weights them by IDF; words that never occur in the corpus get the maximum weight. Coverage is " "the average of (a) the weighted share of question terms found in the best single passage and (b) the share " "found in the top three passages. Evidence is sufficient if the best passage relevance and the coverage " "both exceed calibrated thresholds; partial if slightly below and no question term is absent from the whole " "corpus; otherwise the system abstains and lists the missing terms.") H2("11.3 Conflict-search retrieval and contradiction detection") P("Competing versions of a rule are often outside the top-k (an amendment circular is short and worded " "differently). The verifier therefore re-queries the index with the best evidence sentences and adds " "passages from other documents as conflict candidates. Sentence pairs from different documents are then " "tested: (i) numeric conflict - the same kind of value (%, INR, days, books, dates...) with a different " "number, described by overlapping words, of the type the question asks about, where the question words near " "the value appear in both sentences and the values differ by less than 5x; (ii) polarity conflict - one " "sentence negates a predicate that the other asserts; (iii) NLI contradiction probability above a threshold " "(when the NLI model is available). The issue dates identify the newer document and update cues " "('revised to', 'supersedes', 'extended to') are reported.") H2("11.4 Generation, citation validation and abstention") P("The grounded prompt instructs the LLM to use only numbered passages, cite every sentence, reply " "INSUFFICIENT_EVIDENCE when the answer is absent, present both versions of conflicts and correct false " "premises. Every generated sentence is validated against its cited passage: all numbers must occur in the " "passage and token overlap must exceed a threshold, or the NLI model must predict entailment. Unsupported " "sentences are removed; if none remain the system abstains. Confidence = 0.4 x relevance + 0.4 x coverage " "+ 0.2 x supported-sentence ratio. Each response carries an explanation of the decision.") H2("11.5 Gradio application") P("Seven tabs: Home dashboard, Upload Documents, AI Assistant (chat with follow-up contextualisation and a " "Baseline/EvidenceGuard switch), Evidence Verification, Model Comparison, Evaluation Dashboard (with a " "button that re-runs the full evaluation) and About Project. Every button is wired to a working function; " "this was verified with 21 automated end-to-end interaction tests (Section 14).") for i, (fn, cap) in enumerate([("01_home.png", "Home dashboard with live technology stack"), ("03_assistant.png", "AI Assistant: abstention and an answer from a newly uploaded PDF"), ("04_verification.png", "Evidence Verification tab for a conflicting attendance question"), ("05_comparison.png", "Model Comparison: baseline answers an unanswerable question, EvidenceGuard abstains"), ("06_dashboard.png", "Evaluation Dashboard with real metrics")], 3): p = ROOT / "docs" / "screenshots" / fn if p.exists(): IMG(p, 15.5) CAP(f"Figure {i}. {cap} (actual screenshot of the running application).") BR()
# --------------------------------------------------------------- 12-13 experimental setup & metrics H1("12. Experimental Setup") comps = meta["components"] BUL([f"Hardware: {meta['cpu_count']} CPU cores ({meta['machine']}), no GPU; Python {meta['python']}.", f"Components actually used in the reported run: " + "; ".join(f"{k} = {v}" for k, v in comps.items()) + ".", "Reason: Hugging Face model downloads were blocked in the build environment. The Hugging Face path is " "implemented and was smoke-tested end-to-end with locally built miniature models, but its metrics must be " "produced by re-running scripts/run_evaluation.py --backend full (e.g. on Kaggle or the Space).", f"Split: stratified by category, seed 42: {meta['dev_questions']} DEV questions (threshold calibration only) " f"and {meta['test_questions']} TEST questions.", "Calibrated thresholds: " + ", ".join(f"{k} = {v}" for k, v in CAL["thresholds"].items() if k in ("min_relevance", "min_coverage", "partial_coverage", "min_confidence", "conflict_sentence_coverage", "conflict_topic_sim")) + ".", "Top-k = 5 passages; 20 candidates per retriever before fusion/reranking; RRF k = 60.", f"Total runtime of calibration + 4 x 100 questions: {meta['runtime_s']} s."])
H1("13. Evaluation Metrics") TABLE(["Group", "Metric", "Definition used"], [["Retrieval", "Precision@5 / Recall@5 / MRR", "Gold unit = (document, page) of the evidence; computed over the 85 questions with evidence"], ["Answer", "Answer correctness", "All key facts present (normalised match) for answerable questions; abstention for missing-information questions"], ["Answer", "Expected-behaviour accuracy", "Answer / abstain / flag conflict (with both values) / correct premise, as labelled"], ["Answer", "Faithfulness", "Share of answer sentences whose numbers and >=70% of tokens occur in the retrieved context"], ["Answer", "Evidence-grounded faithfulness", "Same check against the gold evidence pages only"], ["Answer", "Answer relevance", "TF-IDF cosine between question and answer (lexical proxy for RAGAS answer relevance)"], ["Answer", "Context precision / recall", "Rank-weighted AP@5 of gold pages / share of key facts present in the context"], ["Reliability", "Unsupported answer rate", "Non-abstaining answers to unanswerable questions or containing none of the key facts"], ["Reliability", "Abstention accuracy, P/R/F1", "Abstain decision vs. 'missing information' label"], ["Reliability", "Contradiction P/R/F1", "Conflict flag vs. 'conflicting' label"], ["Reliability", "Citation support accuracy", "Share of cited passages that are gold evidence pages"], ["Efficiency", "Response / retrieval / generation time", "Mean wall-clock seconds per question"]], widths=[2.2, 4.4, 9.4], size=7.5) CAP("Table 5. Metrics. Definitions follow RAGAS [7] and ALCE [4] but are computed deterministically against gold labels.") BR()
# --------------------------------------------------------------- 14 results H1("14. Results") P(f"All numbers below are read from results/metrics.json (run of {meta['date']}). " "Experiments use synthetic documents of a fictional university and do not establish real-world accuracy.") keys = [("precision_at_k", "Precision@5"), ("recall_at_k", "Recall@5"), ("mrr", "MRR"), ("answer_correctness", "Answer correctness"), ("behaviour_accuracy", "Expected-behaviour accuracy"), ("faithfulness", "Faithfulness (to context)"), ("grounded_faithfulness", "Evidence-grounded faithfulness"), ("answer_relevance", "Answer relevance (lexical)"), ("context_precision", "Context precision"), ("context_recall", "Context recall"), ("unsupported_answer_rate", "Unsupported answer rate (lower better)"), ("abstention_accuracy", "Abstention accuracy"), ("abstention_precision", "Abstention precision"), ("abstention_recall", "Abstention recall"), ("abstention_f1", "Abstention F1"), ("contradiction_precision", "Contradiction precision"), ("contradiction_recall", "Contradiction recall"), ("contradiction_f1", "Contradiction F1"), ("citation_support_accuracy", "Citation support accuracy"), ("avg_response_time_s", "Avg response time (s)"), ("avg_retrieval_time_s", "Avg retrieval + rerank time (s)"), ("avg_verification_time_s", "Avg verification time (s)"), ("avg_generation_time_s", "Avg generation time (s)")] for split, label, tno in ((T, f"held-out TEST split ({meta['test_questions']} questions)", 6), (A, "all 100 questions", 7)): rows = [[lab] + [f(m(split, c, k), 4 if "time" in k else 3) for c in ORDER] for k, lab in keys] TABLE(["Metric"] + [NAMES[c] for c in ORDER], rows, widths=[5.6, 2.6, 2.6, 2.6, 2.6], size=8) CAP(f"Table {tno}. Four-configuration comparison on the {label}.") IMG(RES / "charts" / "reliability_comparison.png", 16) CAP("Figure 8. Reliability metrics (all 100 questions).") IMG(RES / "charts" / "answer_quality_comparison.png", 16) CAP("Figure 9. Answer quality metrics (all 100 questions).") IMG(RES / "charts" / "retrieval_comparison.png", 16) CAP("Figure 10. Retrieval metrics (all 100 questions).") IMG(RES / "charts" / "category_breakdown.png", 16) CAP("Figure 11. Expected-behaviour accuracy by question category.") IMG(RES / "charts" / "response_time.png", 15) CAP("Figure 12. Mean time per question.") H2("14.1 Statistical significance") TABLE(["Comparison (paired)", "Baseline", "EvidenceGuard", "Difference [95% CI]", "Discordant (EG only / base only)", "Exact McNemar p"], [[name, f"{s['baseline']:.3f}", f"{s['full']:.3f}", f"{s['difference']:+.3f} [{s['ci95'][0]:+.3f}, {s['ci95'][1]:+.3f}]", f"{s['only_other_true']} / {s['only_baseline_true']}", f"{s['mcnemar_exact_p']:.4f}"] for name, s in (("Behaviour accuracy - test", sig_b), ("Behaviour accuracy - all", sig_ba), ("Unsupported answer - test", sig_u), ("Unsupported answer - all", SIG["unsupported_answer|all|baseline_vs_full"]))], widths=[4.2, 1.8, 2.2, 3.4, 2.6, 1.8], size=7.5) CAP("Table 8. Paired significance tests, baseline vs. complete EvidenceGuard (results/significance.json).") rr = SIG["behaviour_accuracy|test|baseline_vs_rerank"] P(f"Reranking alone (configuration 2) did not change behaviour accuracy significantly " f"({rr['difference']:+.3f}, p = {rr['mcnemar_exact_p']:.2f}).") BR()
# --------------------------------------------------------------- 15-16 H1("15. Comparative Analysis") cb, cf = M["by_category"]["baseline"], M["by_category"]["full"] TABLE(["Category", "n", "Baseline behaviour acc.", "EvidenceGuard behaviour acc.", "Baseline abstention rate", "EvidenceGuard abstention rate"], [[c, str(cb[c]["n"]), f(cb[c]["behaviour_accuracy"]), f(cf[c]["behaviour_accuracy"]), f(cb[c]["abstention_rate"]), f(cf[c]["abstention_rate"])] for c in ["answerable", "multi_passage", "missing", "misleading", "conflicting"]], widths=[3.2, 1.0, 3.0, 3.2, 2.8, 2.8], size=8) CAP("Table 9. Per-category comparison (all 100 questions).") BUL([f"RQ1 - unsupported answers: the baseline answered every missing-information question " f"(behaviour accuracy {cb['missing']['behaviour_accuracy']:.2f}); EvidenceGuard abstained correctly on " f"{cf['missing']['behaviour_accuracy']:.0%} of them and lowered the overall unsupported-answer rate from " f"{m(A,'baseline','unsupported_answer_rate'):.2f} to {m(A,'full','unsupported_answer_rate'):.2f}.", f"RQ2 - conflicts: the baseline cannot flag conflicts (F1 = 0 by construction). EvidenceGuard reached " f"precision {m(A,'full','contradiction_precision'):.2f} and recall {m(A,'full','contradiction_recall'):.2f}; " f"the conflict-search retrieval step was needed for amendment circulars that were not in the top-5.", f"RQ3 - cost: answerable accuracy fell from {cb['answerable']['behaviour_accuracy']:.2f} to " f"{cf['answerable']['behaviour_accuracy']:.2f} and multi-passage from {cb['multi_passage']['behaviour_accuracy']:.2f} " f"to {cf['multi_passage']['behaviour_accuracy']:.2f} because of over-abstention; abstention precision is only " f"{m(A,'full','abstention_precision'):.2f}. Mean latency rose from {m(A,'baseline','avg_response_time_s')*1000:.1f} ms " f"to {m(A,'full','avg_response_time_s')*1000:.1f} ms with offline components (an LLM would dominate latency).", "RQ4 - retrieval: recall@5 was already high for the dense LSA baseline on this small corpus, so hybrid " "retrieval and the lexical reranker added little; the improvements come from the verification layer " "(configurations 3 and 4 are almost identical).", f"Note on abstention accuracy: the baseline's {m(A,'baseline','abstention_accuracy'):.2f} is the majority-class rate " "(it never abstains while 85% of questions are answerable); abstention F1 is the informative measure.", "Faithfulness to context is 1.0 for all configurations because the offline extractive composer can only copy " "retrieved sentences; evidence-grounded faithfulness shows the real difference (sentences taken from the right pages)."]) IMG(RES / "charts" / "error_analysis.png", 16) CAP("Figure 13. Error taxonomy, baseline vs. EvidenceGuard (results/error_analysis.csv).") H2("15.1 Failure case examples") ex, seen_t = [], Counter() for e in FAIL["evidenceguard_failures"]: # diverse: at most 2 per error type if seen_t[e["error_type"]] < 2: ex.append(e) seen_t[e["error_type"]] += 1 TABLE(["ID", "Question", "Error type", "EvidenceGuard output (truncated)"], [[e["id"], e["question"], e["error_type"], plain(e["answer"])[:220]] for e in ex], widths=[1.1, 5.0, 3.0, 6.9], size=7) CAP("Table 10. Examples of EvidenceGuard failures (full list in results/failure_cases.json).") wins, seen_c = [], Counter() for w in FAIL["evidenceguard_fixes_over_baseline"]: # one or two per category if seen_c[w["category"]] < (2 if w["category"] == "conflicting" else 1): wins.append(w) seen_c[w["category"]] += 1 TABLE(["ID", "Question", "Baseline answer", "EvidenceGuard answer"], [[w["id"], w["question"], plain(w["baseline_answer"])[:170], plain(w["evidenceguard_answer"])[:170]] for w in wins], widths=[1.1, 4.3, 5.3, 5.3], size=7) CAP("Table 11. Examples where EvidenceGuard corrected a baseline failure.") BR()
H1("16. Discussion") P("The experiment supports the central claim within its scope: a training-free verification layer can stop a " "RAG assistant from answering questions its documents cannot support and can surface conflicting rule " "versions instead of silently choosing one. This matches the failure modes reported in RGB [1] and " "WikiContradict [6], and turns the post-hoc citation evaluation of ALCE [4] into an in-pipeline filter. The " "price is over-abstention, the same trade-off Yoran et al. [5] observed for NLI filtering: when a question " "is paraphrased away from the document wording, or needs two passages, coverage drops below the threshold. " "A practical deployment should therefore present abstentions as 'not found - please check with the office' " "with the retrieved passages visible, which the application does.") P("Two results temper the conclusions. First, the behaviour-accuracy gain partly reflects the benchmark design: " "conflict questions require a conflict flag that the baseline cannot produce. The unsupported-answer rate, " "which does not depend on that design, is the cleaner evidence and is also significant. Second, the rule " "components were designed while inspecting failures on the same question set; only thresholds were " "calibrated on the DEV split. The test results are therefore optimistic and should be confirmed on new, " "independently written questions and on real documents.")
H1("17. Limitations") BUL(LIMITATIONS) H1("18. Future Enhancements") BUL(FUTURE) H1("19. Conclusion") P(f"EvidenceGuard AI demonstrates that evidence verification can be added to a RAG assistant with free, " f"CPU-only components. On a synthetic university benchmark it reduced unsupported answers by " f"{abs(sig_u['difference']):.1%} absolute on held-out questions, detected conflicting rule versions with F1 " f"{m(T,'full','contradiction_f1'):.2f}, and explained every decision, at the cost of some over-abstention. The " "complete system - data generator, two RAG systems, verification module, evaluation suite and seven-tab " "Gradio application - is reproducible from the repository and prepared for Hugging Face Spaces.") BR()
# --------------------------------------------------------------- references H1("20. References") refs = [f"{p['authors']}, \"{p['title']},\" {p['venue']}, {p['year']}. [Online]. Available: {p['link']}" for p in PAPERS] + FOUNDATION B.append({"t": "refs", "items": refs}) H1("Appendix A. Reproducing the results") CODE("pip install -r requirements.txt\npython scripts/generate_dataset.py # 16 PDFs + 100 questions\n" "python scripts/run_evaluation.py --backend lite --llm extractive # this report\n" "python scripts/run_evaluation.py --backend full --llm hf_api # HF models (needs HF_TOKEN)\n" "python scripts/significance.py\npython -m pytest -q\npython app.py")
def readme_table(): meta = M["meta"] keys = [("recall_at_k", "Recall@5"), ("mrr", "MRR"), ("answer_correctness", "Answer correctness"), ("behaviour_accuracy", "Expected-behaviour accuracy"), ("grounded_faithfulness", "Evidence-grounded faithfulness"), ("unsupported_answer_rate", "Unsupported answer rate ↓"), ("abstention_f1", "Abstention F1"), ("contradiction_f1", "Contradiction F1"), ("citation_support_accuracy", "Citation support accuracy"), ("avg_response_time_s", "Avg response time (s)")] lines = [f"Held-out TEST split ({meta['test_questions']} questions), backend `{meta['backend']}` " f"(offline fallback components), run {meta['date']}:\n", "| Metric | " + " | ".join(NAMES[c] for c in ORDER) + " |", "|---|" + "---|" * 4] for k, lab in keys: lines.append(f"| {lab} | " + " | ".join(f(m('test', c, k), 4 if 'time' in k else 3) for c in ORDER) + " |") sb, su = SIG["behaviour_accuracy|test|baseline_vs_full"], SIG["unsupported_answer|test|baseline_vs_full"] lines.append(f"\nPaired exact McNemar test, baseline vs EvidenceGuard (test split): behaviour accuracy " f"{sb['difference']:+.3f} (p = {sb['mcnemar_exact_p']:.3f}); unsupported answers " f"{su['difference']:+.3f} (p = {su['mcnemar_exact_p']:.3f}).") return "\n".join(lines)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--author", default="Leeshal Princia Monteiro") ap.add_argument("--usn", default="SCA25MSD042") ap.add_argument("--programme", default="MSc Data Science, School of Computer Applications") ap.add_argument("--institution", default="Dayananda Sagar University, Bengaluru") a = ap.parse_args() build(a.author, a.usn, a.programme, a.institution) out = ROOT / "reports" out.mkdir(exist_ok=True) (out / "report_model.json").write_text(json.dumps(B, indent=1)) readme = ROOT / "README.md" if readme.exists(): s = readme.read_text() if "<!-- RESULTS_START -->" in s: pre, rest = s.split("<!-- RESULTS_START -->", 1) post = rest.split("<!-- RESULTS_END -->", 1)[1] readme.write_text(pre + "<!-- RESULTS_START -->\n" + readme_table() + "\n<!-- RESULTS_END -->" + post) subprocess.run(["node", str(ROOT / "scripts" / "render_report_docx.js"), str(out / "report_model.json"), str(out / "project_report.docx")], check=True) subprocess.run(["soffice", "--headless", "--convert-to", "pdf", "--outdir", str(out), str(out / "project_report.docx")], check=True, capture_output=True) print("report written:", out / "project_report.docx", out / "project_report.pdf")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618"""Content of the SYNTHETIC university document collection used by EvidenceGuard AI.
Every document belongs to "Aranya Valley University (AVU)", a FICTIONAL institution.Nothing here describes a real university or a real policy. The collection is builtdeliberately to contain: * consistent facts that can be answered from one passage, * facts that need two passages / two documents, * superseded or contradictory versions of the same rule (conflicts C1-C8), * topics that are NOT covered anywhere (for abstention tests), * a distractor document (hostel guidelines) full of look-alike numbers.
Conflicts deliberately planted: C1 minimum attendance 75% (Attendance Regs 2023, Exam Eligibility 2024) vs 80% (Circular 2025) C2 condonation limit 10% / floor 65% (2023) vs 5% / floor 75% (Circular 2025) C3 condonation fee INR 500 (2023) vs INR 1,000 (Circular 2025) C4 scholarship deadline 31 Aug 2025 (Policy, Calendar) vs 15 Sep 2025 (Notice) income ceiling INR 6,00,000 (Policy) vs INR 8,00,000 (Notice) C5 late assignments: 10%/day for 3 days (Assignment Policy) vs not accepted (IA Guidelines) C6 PG borrowing 5 books/14 days, fine INR 5 (Library 2023) vs 6 books/21 days, INR 10 (Notice 2025) C7 add/drop 10 working days (Registration) vs 7 working days (Calendar) C8 pass mark 40% (Grading Policy) vs 50% for PG (PG Handbook) C9 exams start 1 Dec 2025 (Timetable) vs 3 Dec 2025 (Calendar)"""
UNIVERSITY = "Aranya Valley University (AVU)"
# Each document: id, filename, title, doc_no, issued, effective, version, pages (list of# list-of-sections). A section is (heading, [paragraph, ...]). Each inner list = one page.DOCUMENTS = [ # ------------------------------------------------------------------ D01 { "id": "D01", "filename": "01_Attendance_Regulations_2023.pdf", "title": "Attendance Regulations 2023", "doc_no": "AVU/ACAD/ATT/2023", "issued": "2023-06-15", "effective": "2023-07-01", "version": "1.0", "topic": "Attendance regulations", "pages": [ [ ("1. Purpose and Scope", [ "These regulations set out the attendance requirements for all undergraduate and " "postgraduate programmes offered by Aranya Valley University. They apply to every " "theory, laboratory and tutorial course in which a student is registered.", "The regulations are issued by the Office of the Dean of Academics and are binding " "on students, course instructors and Heads of Department.", ]), ("2. Definitions", [ "A contact hour is one scheduled hour of lecture, tutorial or laboratory work. " "Attendance percentage is the number of contact hours attended divided by the number " "of contact hours conducted in a course, multiplied by 100.", ]), ("3. Minimum Attendance Requirement", [ "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.", "Attendance is calculated separately for every course and is not averaged across courses.", ]), ("4. Condonation of Shortage", [ "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.", "A condonation fee of INR 500 per course is payable before the condonation order is issued.", ]), ], [ ("5. Recording and Publication of Attendance", [ "Faculty must upload attendance to the AVU-Learn portal within 48 hours of each class.", "The list of students with attendance shortage is published 7 days before the " "commencement of end-semester examinations.", ]), ("6. Consequences of Shortage", [ "A student who fails to meet the requirement after condonation will be marked NE " "(Not Eligible) and must re-register for the course in a subsequent semester.", ]), ("7. Approved Absences", [ "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.", ]), ("8. Review", [ "These regulations will be reviewed by the Academic Council every two years.", "Issued by: Office of the Dean of Academics, Aranya Valley University (fictional).", ]), ], ], }, # ------------------------------------------------------------------ D02 { "id": "D02", "filename": "02_Circular_Attendance_Amendment_2025.pdf", "title": "Circular: Amendment to Attendance Regulations", "doc_no": "AVU/CIRC/2025/014", "issued": "2025-06-02", "effective": "2025-07-01", "version": "2.0 (amendment)", "topic": "Attendance regulations", "pages": [ [ ("Subject", [ "Amendment to clauses 3 and 4 of the Attendance Regulations 2023 (AVU/ACAD/ATT/2023).", ]), ("Revised Provisions", [ "With effect from the academic year 2025-26, the minimum attendance requirement for each " "course is revised to 80%.", "Condonation on medical grounds is limited to 5% (that is, attendance between 75% and 80%).", "The condonation fee is revised to INR 1,000 per course.", ]), ("Applicability", [ "This circular supersedes clauses 3 and 4 of the Attendance Regulations 2023. All other " "provisions of the Attendance Regulations 2023 remain unchanged.", "Heads of Department are requested to bring this circular to the notice of all students " "at the start of the academic year.", "Issued by: Registrar, Aranya Valley University (fictional), 2 June 2025.", ]), ], ], }, # ------------------------------------------------------------------ D03 { "id": "D03", "filename": "03_Examination_Eligibility_Rules_2024.pdf", "title": "Examination Eligibility Rules 2024", "doc_no": "AVU/EXAM/ELG/2024", "issued": "2024-01-02", "effective": "2024-01-15", "version": "1.0", "topic": "Examination eligibility", "pages": [ [ ("1. Scope", [ "These rules determine whether a student may appear for the end-semester examination " "of a course. They are administered by the Controller of Examinations.", ]), ("2. Conditions of Eligibility", [ "To be eligible for the end-semester examination, a student must satisfy all of the following conditions.", "(a) The student must satisfy the attendance requirement of 75% in the course as per the Attendance Regulations.", "(b) The student must secure at least 40% of the internal assessment marks in the course, " "that is, at least 16 out of 40.", "(c) The student must have no outstanding tuition fee dues.", "(d) The student must have registered for the course in the current semester.", ]), ("3. Hall Tickets", [ "Hall tickets are issued through the AVU-Learn portal 5 days before the first examination.", "A student who is not eligible will not be issued a hall ticket for that course.", ]), ], [ ("4. Appeals", [ "A student may appeal against an eligibility decision to the Controller of Examinations " "within 3 working days of the publication of the eligibility list.", ]), ("5. Library and Other Dues", [ "Library dues do not affect examination eligibility but must be cleared before results are released.", ]), ("6. Students Not Eligible", [ "Students declared not eligible must re-register for the course when it is next offered " "and satisfy all eligibility conditions afresh.", "Issued by: Controller of Examinations, Aranya Valley University (fictional).", ]), ], ], }, # ------------------------------------------------------------------ D04 { "id": "D04", "filename": "04_Internal_Assessment_Guidelines_2024.pdf", "title": "Internal Assessment Guidelines 2024", "doc_no": "AVU/ACAD/IA/2024", "issued": "2024-05-20", "effective": "2024-07-01", "version": "1.0", "topic": "Internal assessment", "pages": [ [ ("1. Mark Distribution", [ "Each theory course carries 100 marks: 40 marks for internal assessment (IA) and 60 marks " "for the end-semester examination.", ]), ("2. Components of Internal Assessment", [ "Internal assessment consists of Internal Test 1 (15 marks), Internal Test 2 (15 marks), " "Assignment (5 marks), and Class participation and quizzes (5 marks).", "Internal tests are of 60 minutes duration and are conducted in the 7th and 13th weeks of the semester.", ]), ("3. Make-up Tests", [ "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.", ]), ], [ ("4. Assignments", [ "Assignments submitted after the deadline will not be accepted for internal assessment.", "Instructors must announce assignment topics at least two weeks before the due date.", ]), ("5. Publication and Review of Marks", [ "IA marks are published on AVU-Learn within 10 working days of each test.", "Students may request a review of IA marks within 5 working days of publication.", ]), ("6. Records", [ "Answer scripts of internal tests are retained by the department for one year.", "Issued by: Office of the Dean of Academics, Aranya Valley University (fictional).", ]), ], ], }, # ------------------------------------------------------------------ D05 { "id": "D05", "filename": "05_Assignment_Submission_Policy_2024.pdf", "title": "Assignment Submission Policy 2024", "doc_no": "AVU/ACAD/ASN/2024", "issued": "2024-06-10", "effective": "2024-07-01", "version": "1.0", "topic": "Assignment submission", "pages": [ [ ("1. Mode of Submission", [ "All assignments must be submitted through the AVU-Learn portal by 11:59 PM on the due date.", "Email submissions are not accepted unless the portal is down, as confirmed by the IT Helpdesk.", "Assignments must be submitted as a single PDF file of no more than 10 MB.", ]), ("2. Late Submission", [ "Late submissions are accepted for up to 3 calendar days after the deadline with a penalty " "of 10% of the maximum marks per day.", "Submissions received more than 3 days late receive zero marks.", ]), ("3. Extensions", [ "Extensions of up to 5 days may be granted by the course instructor on medical or " "compassionate grounds if requested before the deadline.", ]), ], [ ("4. Academic Integrity", [ "Every submission is checked with the university similarity checker.", "A similarity index above 20% requires resubmission within 3 days.", "A similarity index above 40% results in zero marks and referral to the Academic Integrity Committee.", ]), ("5. Group Assignments", [ "Group assignments may have at most 4 members, and each member must state their individual contribution.", "Issued by: Office of the Dean of Academics, Aranya Valley University (fictional).", ]), ], ], }, # ------------------------------------------------------------------ D06 { "id": "D06", "filename": "06_Examination_Timetable_Odd_Semester_2025.pdf", "title": "End-Semester Examination Timetable - Odd Semester 2025-26", "doc_no": "AVU/EXAM/TT/2025/ODD", "issued": "2025-10-20", "effective": "2025-10-20", "version": "1.0", "topic": "Examination timetable", "pages": [ [ ("1. Examination Period", [ "The odd semester end-semester examinations commence on 1 December 2025 and conclude on 12 December 2025.", "Morning session: 10:00 AM to 1:00 PM. Afternoon session: 2:00 PM to 5:00 PM.", "Students must report 30 minutes before the start of the session. No student is admitted " "more than 30 minutes after the start of the session.", ]), ("2. MSc Data Science - Semester 3", [ "01 December 2025 (Monday): MDS301 Deep Learning - Morning session.", "03 December 2025 (Wednesday): MDS302 Generative AI and LLMs - Morning session.", "05 December 2025 (Friday): MDS303 Advanced Algorithms and Optimisation - Morning session.", "08 December 2025 (Monday): MDS304 Information Systems Engineering - Morning session.", "10 December 2025 (Wednesday): MDS305 Security for Data Science - Afternoon session.", ]), ], [ ("3. MBA - Semester 3", [ "02 December 2025 (Tuesday): MBA301 Financial Management - Morning session.", "04 December 2025 (Thursday): MBA302 Marketing Analytics - Afternoon session.", "09 December 2025 (Tuesday): MBA303 Strategic Management - Morning session.", ]), ("4. BSc Computer Science - Semester 5", [ "01 December 2025 (Monday): BCS501 Operating Systems - Afternoon session.", "04 December 2025 (Thursday): BCS502 Computer Networks - Morning session.", "11 December 2025 (Thursday): BCS503 Software Engineering - Morning session.", ]), ("5. General Instructions", [ "Only non-programmable scientific calculators are permitted in the examination hall.", "Results of the odd semester examinations will be announced by 15 January 2026.", "Issued by: Controller of Examinations, Aranya Valley University (fictional), 20 October 2025.", ]), ], ], }, # ------------------------------------------------------------------ D07 { "id": "D07", "filename": "07_Scholarship_Policy_2025-26.pdf", "title": "Scholarship Policy 2025-26", "doc_no": "AVU/SCH/2025", "issued": "2025-05-01", "effective": "2025-05-01", "version": "1.0", "topic": "Scholarship eligibility", "pages": [ [ ("1. Merit Scholarship", [ "Students with a CGPA of 9.0 or above in the previous academic year receive a 50% tuition fee waiver.", "Students with a CGPA between 8.5 and 8.99 receive a 25% tuition fee waiver.", ]), ("2. Need-based Scholarship", [ "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.", "Applicants must submit an income certificate issued by a competent authority within the " "last 6 months and the marks card of the previous year.", ]), ("3. Application", [ "Applications must be submitted on AVU-Learn by 31 August 2025.", ]), ], [ ("4. Conditions", [ "A student may hold only one university scholarship at a time; if eligible for more than one, " "the higher-value scholarship is awarded.", "Students may simultaneously hold one external (government or private) scholarship.", "Scholarship holders must maintain a minimum of 75% attendance in every course.", ]), ("5. Renewal", [ "Scholarships are renewed annually subject to a CGPA of at least 8.0 and no disciplinary action.", "Issued by: Scholarship Cell, Aranya Valley University (fictional), 1 May 2025.", ]), ], ], }, # ------------------------------------------------------------------ D08 { "id": "D08", "filename": "08_Scholarship_Revised_Notice_2025.pdf", "title": "Notice: Revision of Scholarship Deadline and Income Ceiling", "doc_no": "AVU/SCH/NOT/2025/07", "issued": "2025-08-25", "effective": "2025-08-25", "version": "1.1 (notice)", "topic": "Scholarship eligibility", "pages": [ [ ("Notice", [ "The last date for scholarship applications for 2025-26 is extended to 15 September 2025.", "The family income ceiling for the need-based scholarship is revised to INR 8,00,000.", "All other conditions of the Scholarship Policy 2025-26 remain unchanged.", "Issued by: Scholarship Cell, Aranya Valley University (fictional), 25 August 2025.", ]), ], ], }, # ------------------------------------------------------------------ D09 { "id": "D09", "filename": "09_Course_Registration_Guidelines_2025.pdf", "title": "Course Registration Guidelines 2025", "doc_no": "AVU/ACAD/REG/2025", "issued": "2025-06-05", "effective": "2025-07-01", "version": "1.0", "topic": "Course registration", "pages": [ [ ("1. Registration Window", [ "Course registration for the odd semester opens on 1 July 2025 and closes on 15 July 2025.", "Late registration is permitted until 22 July 2025 with a late fee of INR 2,000.", "Registration requires clearance of previous semester fees and approval of the faculty advisor.", ]), ("2. Credit Limits", [ "PG students must register for a minimum of 18 and a maximum of 26 credits per semester.", "Audit courses do not count toward credit limits.", "A student may register for a maximum of 2 open electives per semester.", ]), ], [ ("3. Add and Drop", [ "Students may add or drop elective courses within 10 working days from the start of classes.", "Core courses cannot be dropped.", ]), ("4. Prerequisites", [ "A student may register for a course only after passing its prerequisite courses, as listed in the programme structure.", "Issued by: Office of the Dean of Academics, Aranya Valley University (fictional).", ]), ], ], }, # ------------------------------------------------------------------ D10 { "id": "D10", "filename": "10_Academic_Leave_Policy_2024.pdf", "title": "Academic Leave Policy 2024", "doc_no": "AVU/ACAD/LV/2024", "issued": "2024-03-11", "effective": "2024-07-01", "version": "1.0", "topic": "Academic leave", "pages": [ [ ("1. Leave of Absence", [ "A student may apply for academic leave (leave of absence) for a maximum of two semesters " "during the entire programme.", "Applications must be submitted to the Dean of Academics at least 30 days before the start of " "the semester, except in medical emergencies.", "Students may avail maternity leave of up to 6 months, which is counted within the academic leave limit.", ]), ("2. Medical Leave", [ "Medical leave of up to 15 days within a semester may be approved by the Head of Department on " "submission of a medical certificate from a registered medical practitioner.", "Approved medical leave does not count as attendance; it is considered only for condonation.", ]), ], [ ("3. Fees During Leave", [ "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. Duration and Return", [ "The maximum duration to complete a programme is the normal duration plus two years, including any academic leave.", "Students returning from leave must re-register within the regular registration window.", "Issued by: Office of the Dean of Academics, Aranya Valley University (fictional).", ]), ], ], }, # ------------------------------------------------------------------ D11 { "id": "D11", "filename": "11_Library_Regulations_2023.pdf", "title": "Central Library Regulations 2023", "doc_no": "AVU/LIB/2023", "issued": "2023-07-01", "effective": "2023-07-01", "version": "1.0", "topic": "Library regulations", "pages": [ [ ("1. Library Hours", [ "The Central Library is open from 8:00 AM to 10:00 PM on working days and from 9:00 AM to " "5:00 PM on Saturdays. It remains closed on Sundays and university holidays.", "A valid university ID card is mandatory for entry.", ]), ("2. Borrowing Limits", [ "Undergraduate students may borrow up to 3 books for 14 days.", "Postgraduate students may borrow up to 5 books for 14 days.", "Research scholars may borrow up to 8 books for 30 days.", ]), ], [ ("3. Renewal and Reference Books", [ "A borrowed book may be renewed once if it has not been reserved by another member.", "Reference books cannot be borrowed and must be used within the library.", ]), ("4. Fines and Losses", [ "An overdue fine of INR 5 per book per day is charged.", "Lost books must be replaced or paid for at twice the current price.", ]), ("5. Electronic Resources", [ "Subscribed e-journals can be accessed off campus through the library remote access service using university credentials.", "Issued by: University Librarian, Aranya Valley University (fictional).", ]), ], ], }, # ------------------------------------------------------------------ D12 { "id": "D12", "filename": "12_Library_Notice_2025.pdf", "title": "Library Notice: Revised Borrowing Rules", "doc_no": "AVU/LIB/NOT/2025/03", "issued": "2025-07-10", "effective": "2025-08-01", "version": "2.0 (notice)", "topic": "Library regulations", "pages": [ [ ("Notice", [ "With effect from 1 August 2025, postgraduate students may borrow up to 6 books for a period of 21 days.", "The overdue fine is revised to INR 10 per book per day.", "Library hours during examination periods are extended until 12:00 midnight on working days.", "Issued by: University Librarian, Aranya Valley University (fictional), 10 July 2025.", ]), ], ], }, # ------------------------------------------------------------------ D13 { "id": "D13", "filename": "13_Grading_and_Academic_Progression_Policy_2024.pdf", "title": "Grading and Academic Progression Policy 2024", "doc_no": "AVU/ACAD/GRD/2024", "issued": "2024-04-02", "effective": "2024-07-01", "version": "1.0", "topic": "Grading and academic progression", "pages": [ [ ("1. Grading Scale", [ "Grades are awarded on a 10-point scale as follows.", "Grade O (grade point 10): 90 to 100 marks. Grade A+ (grade point 9): 80 to 89 marks. " "Grade A (grade point 8): 70 to 79 marks. Grade B+ (grade point 7): 60 to 69 marks. " "Grade B (grade point 6): 50 to 59 marks. Grade C (grade point 5): 40 to 49 marks. " "Grade F (grade point 0): below 40 marks.", ]), ("2. Passing a Course", [ "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).", ]), ("3. SGPA and CGPA", [ "SGPA is the credit-weighted average of grade points in a semester; CGPA is the credit-weighted " "average of grade points over all completed semesters.", ]), ], [ ("4. Progression", [ "A student with more than 4 backlog courses at the end of an academic year will not be promoted to the next year.", "Supplementary examinations are held in June and July; the maximum grade awarded in a supplementary examination is grade A.", ]), ("5. Classification", [ "First Class with Distinction is awarded for a CGPA of 8.0 or above. First Class is awarded for a " "CGPA from 6.5 to 7.99. Second Class is awarded for a CGPA from 5.5 to 6.49.", "Issued by: Controller of Examinations, Aranya Valley University (fictional).", ]), ], ], }, # ------------------------------------------------------------------ D14 { "id": "D14", "filename": "14_Academic_Calendar_2025-26.pdf", "title": "Academic Calendar 2025-26 (Odd Semester)", "doc_no": "AVU/CAL/2025-26", "issued": "2025-06-15", "effective": "2025-07-01", "version": "1.0", "topic": "Academic calendar", "pages": [ [ ("1. Key Dates - Odd Semester 2025-26", [ "Odd semester classes begin on 21 July 2025.", "Add/drop period for electives: 7 working days from the start of classes.", "Last date for scholarship applications: 31 August 2025.", "Internal Test 1: 1 September 2025 to 5 September 2025.", "Internal Test 2: 13 October 2025 to 17 October 2025.", "Last working day of the odd semester: 21 November 2025.", "End-semester examinations: from 3 December 2025.", ]), ], [ ("2. Holidays", [ "Ganesh Chaturthi: 27 August 2025. Gandhi Jayanti: 2 October 2025. Deepavali: 20 and 21 October 2025.", ]), ("3. Even Semester", [ "Even semester classes begin on 5 January 2026.", "Issued by: Office of the Dean of Academics, Aranya Valley University (fictional), 15 June 2025.", ]), ], ], }, # ------------------------------------------------------------------ D15 { "id": "D15", "filename": "15_PG_Programme_Handbook_Extract_2025.pdf", "title": "Postgraduate Programme Handbook 2025-26 (Extract)", "doc_no": "AVU/PG/HB/2025", "issued": "2025-07-05", "effective": "2025-07-21", "version": "1.0", "topic": "Grading and academic progression", "pages": [ [ ("1. About this Handbook", [ "This handbook summarises key academic rules for postgraduate (PG) students. Where it differs " "from a university regulation, students should seek clarification from the Dean of Academics.", ]), ("2. Passing Standard for PG Courses", [ "PG students must obtain at least 50% marks in aggregate to pass a course.", ]), ("3. Dissertation", [ "The PG dissertation carries 12 credits and is evaluated by an internal guide and an external examiner.", "Issued by: Office of Postgraduate Studies, Aranya Valley University (fictional).", ]), ], ], }, # ------------------------------------------------------------------ D16 (distractor) { "id": "D16", "filename": "16_Hostel_and_Campus_Facilities_Guidelines_2025.pdf", "title": "Hostel and Campus Facilities Guidelines 2025", "doc_no": "AVU/HOSTEL/2025", "issued": "2025-06-20", "effective": "2025-07-01", "version": "1.0", "topic": "Hostel and facilities (distractor)", "pages": [ [ ("1. Hostel Timings", [ "Hostel residents must be inside the hostel premises by 9:30 PM on all days.", "Guests may stay in the hostel guest room for a maximum of 2 days with prior permission of the warden.", ]), ("2. Fees", [ "The mess fee is INR 4,500 per month, payable by the 10th of each month.", "Late payment of hostel dues attracts a fine of INR 500.", ]), ("3. Allotment", [ "75% of hostel rooms are reserved for first-year students. Room allotment is valid for one academic year.", ]), ], [ ("4. Campus Facilities", [ "The gymnasium is open from 6:00 AM to 9:00 AM and from 5:00 PM to 8:00 PM.", "Campus Wi-Fi is available to residents with a daily limit of 5 GB.", "Issued by: Chief Warden, Aranya Valley University (fictional).", ]), ], ], },]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"""Regenerates the complete SYNTHETIC dataset for EvidenceGuard AI:
1. sample_data/*.pdf - 16 fictional university documents (real PDFs) 2. sample_data/corpus_manifest.json - metadata for every document 3. evaluation_data/questions.json - 100 evaluation questions with evidence pages 4. evaluation_data/questions.csv - same, flattened
Every evidence phrase is located in the extracted PDF text; the script fails loudly ifany phrase cannot be found, so the questions are guaranteed to be derived from the PDFs.
Usage: python scripts/generate_dataset.py"""from __future__ import annotations
import csvimport jsonimport sysfrom collections import Counterfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT))sys.path.insert(0, str(ROOT / "scripts"))
from reportlab.lib import colors # noqa: E402from reportlab.lib.enums import TA_CENTER # noqa: E402from reportlab.lib.pagesizes import A4 # noqa: E402from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet # noqa: E402from reportlab.lib.units import cm # noqa: E402from reportlab.platypus import (PageBreak, Paragraph, SimpleDocTemplate, # noqa: E402 Spacer, Table, TableStyle)
from corpus_content import DOCUMENTS, UNIVERSITY # noqa: E402from questions_spec import Q # noqa: E402from src.text_utils import normalize # noqa: E402
SAMPLE = ROOT / "sample_data"EVAL = ROOT / "evaluation_data"BANNER = "SYNTHETIC DEMONSTRATION DATA - fictional university, not a real policy"
def _styles(): ss = getSampleStyleSheet() return { "title": ParagraphStyle("t", parent=ss["Title"], fontSize=16, leading=20, spaceAfter=6), "sub": ParagraphStyle("s", parent=ss["Normal"], fontSize=9.5, alignment=TA_CENTER, textColor=colors.HexColor("#444444")), "h": ParagraphStyle("h", parent=ss["Heading2"], fontSize=12, spaceBefore=10, spaceAfter=4), "p": ParagraphStyle("p", parent=ss["Normal"], fontSize=10.5, leading=14.5, spaceAfter=6), }
def render_pdf(doc: dict, path: Path) -> None: st = _styles() total_pages = len(doc["pages"])
def on_page(canvas, d): canvas.saveState() canvas.setFillColor(colors.HexColor("#B00020")) canvas.setFont("Helvetica-Bold", 8.5) canvas.drawCentredString(A4[0] / 2, A4[1] - 1.1 * cm, BANNER) canvas.setFillColor(colors.HexColor("#555555")) canvas.setFont("Helvetica", 8.5) canvas.drawString(2 * cm, 1.2 * cm, f"{doc['doc_no']} | {doc['title']}") canvas.drawRightString(A4[0] - 2 * cm, 1.2 * cm, f"Page {d.page} of {total_pages}") canvas.restoreState()
flow = [ Paragraph(UNIVERSITY + " (fictional)", st["sub"]), Paragraph(doc["title"], st["title"]), ] meta = Table( [["Document No.", doc["doc_no"], "Version", doc["version"]], ["Issued", doc["issued"], "Effective from", doc["effective"]]], colWidths=[3.0 * cm, 5.2 * cm, 3.0 * cm, 5.0 * cm], ) meta.setStyle(TableStyle([ ("FONT", (0, 0), (-1, -1), "Helvetica", 9), ("FONT", (0, 0), (0, -1), "Helvetica-Bold", 9), ("FONT", (2, 0), (2, -1), "Helvetica-Bold", 9), ("GRID", (0, 0), (-1, -1), 0.4, colors.grey), ("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#F4F6F8")), ])) flow += [meta, Spacer(1, 8)] for pi, page in enumerate(doc["pages"]): if pi > 0: flow.append(PageBreak()) for heading, paras in page: flow.append(Paragraph(heading, st["h"])) for para in paras: flow.append(Paragraph(para, st["p"])) SimpleDocTemplate(str(path), pagesize=A4, topMargin=2 * cm, bottomMargin=2 * cm, leftMargin=2 * cm, rightMargin=2 * cm, title=doc["title"], author="EvidenceGuard AI synthetic data generator", subject=BANNER).build(flow, onFirstPage=on_page, onLaterPages=on_page)
def extract_pages(path: Path) -> list[str]: import pymupdf with pymupdf.open(str(path)) as pdf: return [p.get_text() for p in pdf]
def main() -> None: SAMPLE.mkdir(exist_ok=True) EVAL.mkdir(exist_ok=True) manifest, page_text = [], {} for doc in DOCUMENTS: path = SAMPLE / doc["filename"] render_pdf(doc, path) pages = extract_pages(path) assert len(pages) == len(doc["pages"]), f"{doc['id']}: expected {len(doc['pages'])} pages, got {len(pages)}" page_text[doc["id"]] = [normalize(p) for p in pages] manifest.append({k: doc[k] for k in ("id", "filename", "title", "doc_no", "issued", "effective", "version", "topic")} | {"pages": len(pages)}) (SAMPLE / "corpus_manifest.json").write_text(json.dumps(manifest, indent=2)) by_id = {d["id"]: d for d in DOCUMENTS}
rows = [] for q in Q: ev = [] for doc_id, phrase in q["evidence"]: pages = [i + 1 for i, t in enumerate(page_text[doc_id]) if normalize(phrase) in t] if not pages: raise SystemExit(f"[{q['id']}] evidence phrase not found in {doc_id}: {phrase!r}") ev.append({"doc_id": doc_id, "document": by_id[doc_id]["filename"], "title": by_id[doc_id]["title"], "page": pages[0], "phrase": phrase}) for kw in q["keywords"]: # every key fact must exist in its evidence alts = [normalize(a).strip() for a in kw.split("|")] if ev and not any(any(a in page_text[e["doc_id"]][e["page"] - 1] for a in alts) for e in ev): raise SystemExit(f"[{q['id']}] keyword {kw!r} not present in its evidence pages") rows.append({ "id": q["id"], "category": q["category"], "question": q["question"], "expected_answer": q["expected_answer"], "answer_keywords": q["keywords"], "evidence": ev, "supporting_document": "; ".join(sorted({e["document"] for e in ev})) or "NONE", "supporting_page": "; ".join(f"{e['doc_id']} p.{e['page']}" for e in ev) or "NONE", "expected_evidence_status": q["status"], "expected_behaviour": q["behaviour"], })
(EVAL / "questions.json").write_text(json.dumps(rows, indent=2)) with open(EVAL / "questions.csv", "w", newline="") as f: w = csv.DictWriter(f, fieldnames=["id", "category", "question", "expected_answer", "answer_keywords", "supporting_document", "supporting_page", "expected_evidence_status", "expected_behaviour"]) w.writeheader() for r in rows: w.writerow({k: ("; ".join(r[k]) if k == "answer_keywords" else r[k]) for k in w.fieldnames})
print(f"Generated {len(manifest)} PDFs ({sum(m['pages'] for m in manifest)} pages) in {SAMPLE}") print(f"Generated {len(rows)} questions:", dict(Counter(r["category"] for r in rows)))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""Draws assets/architecture.png and assets/workflow.png with matplotlib (no external tools)."""from pathlib import Path
import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as plt # noqa: E402from matplotlib.patches import FancyArrowPatch, FancyBboxPatch # noqa: E402
ASSETS = Path(__file__).resolve().parents[1] / "assets"ASSETS.mkdir(exist_ok=True)INK, MUTED, SURF = "#0b0b0b", "#52514e", "#fcfcfb"BLUE, ORANGE, AQUA, YELLOW = "#cde2fb", "#fbdccd", "#c9eedf", "#fbe7b5"EDGE = {BLUE: "#2a78d6", ORANGE: "#eb6834", AQUA: "#1baf7a", YELLOW: "#c98500", "#eeeeea": "#8a8986"}
def box(ax, x, y, w, h, text, fill, size=9, bold=False): ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.02,rounding_size=0.08", fc=fill, ec=EDGE.get(fill, "#8a8986"), lw=1.3)) ax.text(x + w / 2, y + h / 2, text, ha="center", va="center", fontsize=size, color=INK, fontweight="bold" if bold else "normal", wrap=True)
def arrow(ax, x1, y1, x2, y2, color=MUTED, style="-|>", ls="-"): ax.add_patch(FancyArrowPatch((x1, y1), (x2, y2), arrowstyle=style, mutation_scale=12, color=color, lw=1.3, linestyle=ls, shrinkA=2, shrinkB=2))
def architecture(): fig, ax = plt.subplots(figsize=(13, 7.4)) ax.set_xlim(0, 13) ax.set_ylim(0, 7.4) ax.axis("off") fig.patch.set_facecolor(SURF) ax.text(0.2, 7.05, "EvidenceGuard AI - system architecture", fontsize=14, fontweight="bold", color=INK)
# ingestion layer ax.text(0.2, 6.45, "Ingestion layer", fontsize=10, color=MUTED, fontweight="bold") box(ax, 0.2, 5.4, 1.9, 0.85, "PDF upload /\nsample_data", "#eeeeea") box(ax, 2.5, 5.4, 2.1, 0.85, "Text extraction\n(PyMuPDF / pypdf)", BLUE) box(ax, 5.0, 5.4, 2.1, 0.85, "Cleaning +\nmetadata (title, date)", BLUE) box(ax, 7.5, 5.4, 2.1, 0.85, "Sentence-aware\nchunking (70 words)", BLUE) box(ax, 10.0, 5.95, 2.8, 0.6, "Embeddings -> FAISS index", BLUE, 8.5) box(ax, 10.0, 5.2, 2.8, 0.6, "BM25 keyword index", BLUE, 8.5) for x in (2.1, 4.6, 7.1): arrow(ax, x, 5.82, x + 0.4, 5.82) arrow(ax, 9.6, 5.9, 10.0, 6.2) arrow(ax, 9.6, 5.75, 10.0, 5.5)
# system A ax.text(0.2, 4.65, "System A - Baseline RAG", fontsize=10, color=MUTED, fontweight="bold") box(ax, 0.2, 3.75, 2.2, 0.7, "Question", "#eeeeea") box(ax, 2.8, 3.75, 2.4, 0.7, "Dense retrieval\n(top-5, FAISS)", BLUE) box(ax, 5.6, 3.75, 2.4, 0.7, "LLM answer\n+ citations", ORANGE) box(ax, 8.4, 3.75, 2.0, 0.7, "Answer\n(always)", "#eeeeea") arrow(ax, 2.4, 4.1, 2.8, 4.1) arrow(ax, 5.2, 4.1, 5.6, 4.1) arrow(ax, 8.0, 4.1, 8.4, 4.1)
# system B ax.text(0.2, 3.15, "System B - EvidenceGuard RAG", fontsize=10, color=MUTED, fontweight="bold") y = 2.05 steps = [("Hybrid retrieval\nFAISS + BM25 (RRF)", BLUE), ("Cross-encoder\nreranking", BLUE), ("Evidence\nsufficiency", AQUA), ("Conflict search +\ncontradiction (NLI\n+ numeric rules)", AQUA), ("Grounded LLM\ngeneration", ORANGE), ("Citation\nvalidation", AQUA), ("Confidence +\nabstention", YELLOW)] x = 0.2 w = 1.68 for i, (t, c) in enumerate(steps): box(ax, x, y, w, 0.95, t, c, 8.2) if i: arrow(ax, x - 0.14, y + 0.47, x, y + 0.47) x += w + 0.14 box(ax, 0.2, 0.5, 3.6, 0.95, "ANSWERED / PARTIAL /\nCONFLICT WARNING / ABSTAINED", YELLOW, 8.5, True) 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) box(ax, 8.8, 0.5, 4.0, 0.95, "Gradio UI: chat, evidence panel,\nside-by-side comparison, evaluation dashboard", "#eeeeea", 8.3) arrow(ax, x - 0.14 - w / 2, y, 2.0, 1.45) arrow(ax, 3.8, 0.97, 4.2, 0.97) arrow(ax, 8.4, 0.97, 8.8, 0.97) arrow(ax, 11.4, 5.2, 11.4, 4.45, ls="--") ax.text(11.5, 4.75, "shared indexes", fontsize=8, color=MUTED) ax.text(0.2, 0.12, "Blue = retrieval · Green = verification (EvidenceGuard contribution) · Orange = LLM · " "Yellow = decision. Every model has an offline fallback (LSA embeddings, lexical reranker, rule verifier, " "extractive composer).", fontsize=8, color=MUTED) fig.savefig(ASSETS / "architecture.png", dpi=160, bbox_inches="tight", facecolor=SURF) plt.close(fig)
def workflow(): fig, ax = plt.subplots(figsize=(8.6, 10.5)) ax.set_xlim(0, 8.6) ax.set_ylim(0, 10.5) ax.axis("off") fig.patch.set_facecolor(SURF) ax.text(0.2, 10.15, "EvidenceGuard AI - decision workflow", fontsize=14, fontweight="bold", color=INK) cx, w, h = 1.0, 4.0, 0.62 ys = [9.2, 8.25, 7.3, 6.35, 5.4, 4.45, 3.5, 2.55] labels = [("User question (+ follow-up context)", "#eeeeea"), ("Hybrid retrieval: FAISS + BM25, fused by RRF", BLUE), ("Cross-encoder reranking -> top-5 passages", BLUE), ("Evidence sufficiency: relevance & coverage", AQUA), ("Conflict-search retrieval + contradiction check", AQUA), ("Context-grounded generation (conflict-aware)", ORANGE), ("Citation validation of every sentence", AQUA), ("Confidence = 0.4 rel + 0.4 cov + 0.2 support", YELLOW)] for (t, c), y in zip(labels, ys): box(ax, cx, y, w, h, t, c, 8.8) for a, b in zip(ys, ys[1:]): arrow(ax, cx + w / 2, a, cx + w / 2, b + h) # side exits box(ax, 5.6, 6.35, 2.8, h, "ABSTAIN: insufficient\nevidence (+ missing terms)", YELLOW, 8) arrow(ax, cx + w, 6.35 + h / 2, 5.6, 6.35 + h / 2) ax.text(5.08, 6.88, "insufficient", fontsize=7.5, color=MUTED) box(ax, 5.6, 4.45, 2.8, h, "Conflict note: both versions,\ndates, newer document", "#eeeeea", 8) arrow(ax, 5.6, 4.45 + h / 2, cx + w, 4.45 + h / 2, ls="--") box(ax, 5.6, 3.5, 2.8, h, "Drop unsupported sentences;\nnone left -> ABSTAIN", YELLOW, 8) arrow(ax, cx + w, 3.5 + h / 2, 5.6, 3.5 + h / 2) outs = [("ANSWERED", 0.2), ("PARTIAL", 2.2), ("CONFLICT\nWARNING", 4.2), ("ABSTAINED", 6.2)] for t, x in outs: box(ax, x, 1.1, 1.8, 0.75, t, YELLOW, 8.5, True) arrow(ax, cx + w / 2, 2.55, x + 0.9, 1.85) box(ax, 0.2, 0.15, 7.8, 0.6, "Explanation + evidence panel (passages, scores, conflicts, citation checks) shown to the user", "#eeeeea", 8.5) fig.savefig(ASSETS / "workflow.png", dpi=160, bbox_inches="tight", facecolor=SURF) plt.close(fig)
if __name__ == "__main__": architecture() workflow() print("diagrams written to", ASSETS)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334"""Evaluation question specification (100 questions) for the SYNTHETIC AVU corpus.
Fields id, category, question, expected_answer, keywords : list of key facts that a correct answer must contain (normalised match; an item "a|b" means either a or b is acceptable), evidence : list of (doc_id, exact phrase) - the page is located automatically, status : expected evidence status -> sufficient | insufficient | conflicting behaviour : expected system behaviour -> answer | abstain | flag_conflict | correct_premise
Categories: answerable (30), multi_passage (20), missing (15), misleading (15), conflicting (20)"""
Q = []
def add(qid, cat, question, answer, keywords, evidence, status, behaviour): Q.append(dict(id=qid, category=cat, question=question, expected_answer=answer, keywords=keywords, evidence=evidence, status=status, behaviour=behaviour))
# ----------------------------------------------------------------- answerable (30)A = "answerable"add("A01", A, "How many marks are allotted to internal assessment in a theory course?", "40 marks are allotted to internal assessment (the end-semester exam carries 60).", ["40 marks"], [("D04", "40 marks for internal assessment")], "sufficient", "answer")add("A02", A, "How many marks does the end-semester examination of a theory course carry?", "60 marks.", ["60 marks"], [("D04", "60 marks for the end-semester examination")], "sufficient", "answer")add("A03", A, "What is the duration of an internal test?", "Internal tests are 60 minutes long.", ["60 minutes"], [("D04", "Internal tests are of 60 minutes duration")], "sufficient", "answer")add("A04", A, "Within how many working days must a medical certificate be submitted to take a make-up test?", "Within 3 working days of the missed test.", ["3 working days"], [("D04", "medical certificate is submitted within 3 working days of the missed test")], "sufficient", "answer")add("A05", A, "By what time on the due date must assignments be submitted on AVU-Learn?", "By 11:59 PM on the due date.", ["11:59"], [("D05", "by 11:59 PM on the due date")], "sufficient", "answer")add("A06", A, "What is the maximum file size allowed for an assignment submission?", "A single PDF of no more than 10 MB.", ["10 mb"], [("D05", "single PDF file of no more than 10 MB")], "sufficient", "answer")add("A07", A, "What is the maximum number of members allowed in a group assignment?", "At most 4 members.", ["4 members"], [("D05", "at most 4 members")], "sufficient", "answer")add("A08", A, "What happens if an assignment has a similarity index above 40%?", "It receives zero marks and is referred to the Academic Integrity Committee.", ["zero marks", "academic integrity committee"], [("D05", "A similarity index above 40% results in zero marks")], "sufficient", "answer")add("A09", A, "On what date do the odd semester end-semester examinations conclude?", "12 December 2025.", ["12 december 2025"], [("D06", "conclude on 12 December 2025")], "sufficient", "answer")add("A10", A, "What are the timings of the afternoon examination session?", "2:00 PM to 5:00 PM.", ["2:00 pm", "5:00 pm"], [("D06", "Afternoon session: 2:00 PM to 5:00 PM")], "sufficient", "answer")add("A11", A, "How early must students report before an examination session starts?", "30 minutes before the start of the session.", ["30 minutes"], [("D06", "Students must report 30 minutes before the start of the session")], "sufficient", "answer")add("A12", A, "On which date is the MDS302 Generative AI and LLMs examination?", "03 December 2025, morning session.", ["03 december 2025|3 december 2025"], [("D06", "MDS302 Generative AI and LLMs")], "sufficient", "answer")add("A13", A, "What type of calculator is permitted in the examination hall?", "Only non-programmable scientific calculators.", ["non-programmable"], [("D06", "Only non-programmable scientific calculators are permitted")], "sufficient", "answer")add("A14", A, "By when will the odd semester examination results be announced?", "By 15 January 2026.", ["15 january 2026"], [("D06", "will be announced by 15 January 2026")], "sufficient", "answer")add("A15", A, "What tuition fee waiver does a student with a CGPA of 9.0 or above receive?", "A 50% tuition fee waiver.", ["50%"], [("D07", "CGPA of 9.0 or above in the previous academic year receive a 50% tuition fee waiver")], "sufficient", "answer")add("A16", A, "What tuition fee waiver is given to students with a CGPA between 8.5 and 8.99?", "A 25% tuition fee waiver.", ["25%"], [("D07", "between 8.5 and 8.99 receive a 25% tuition fee waiver")], "sufficient", "answer")add("A17", A, "What is the amount of the need-based scholarship?", "INR 30,000 per year.", ["30000"], [("D07", "need-based scholarship of INR 30,000 per year")], "sufficient", "answer")add("A18", A, "What CGPA is required for a scholarship to be renewed?", "A CGPA of at least 8.0 (and no disciplinary action).", ["8.0"], [("D07", "renewed annually subject to a CGPA of at least 8.0")], "sufficient", "answer")add("A19", A, "Can a student hold an external scholarship together with a university scholarship?", "Yes, a student may simultaneously hold one external (government or private) scholarship.", ["one external"], [("D07", "simultaneously hold one external")], "sufficient", "answer")add("A20", A, "How many credits must a PG student register for in a semester?", "A minimum of 18 and a maximum of 26 credits.", ["18", "26"], [("D09", "minimum of 18 and a maximum of 26 credits per semester")], "sufficient", "answer")add("A21", A, "What is the fee for late course registration?", "INR 2,000 (late registration allowed until 22 July 2025).", ["2000"], [("D09", "with a late fee of INR 2,000")], "sufficient", "answer")add("A22", A, "How many open electives can a student register for per semester?", "A maximum of 2 open electives per semester.", ["2 open electives"], [("D09", "maximum of 2 open electives per semester")], "sufficient", "answer")add("A23", A, "For how many semesters can a student take academic leave during the programme?", "A maximum of two semesters.", ["two semesters"], [("D10", "maximum of two semesters")], "sufficient", "answer")add("A24", A, "How far in advance must an application for academic leave be submitted?", "At least 30 days before the start of the semester (except medical emergencies).", ["30 days"], [("D10", "at least 30 days before the start of the semester")], "sufficient", "answer")add("A25", A, "What fee must a student pay per semester while on academic leave?", "A registration retention fee of INR 5,000 per semester (no tuition fee).", ["5000"], [("D10", "registration retention fee of INR 5,000 per semester")], "sufficient", "answer")add("A26", A, "What is the maximum duration allowed to complete a programme?", "The normal duration plus two years, including any academic leave.", ["two years"], [("D10", "normal duration plus two years")], "sufficient", "answer")add("A27", A, "What are the Central Library's opening hours on Saturdays?", "9:00 AM to 5:00 PM.", ["9:00 am", "5:00 pm"], [("D11", "from 9:00 AM to 5:00 PM on Saturdays")], "sufficient", "answer")add("A28", A, "How many books can research scholars borrow and for how long?", "Up to 8 books for 30 days.", ["8 books", "30 days"], [("D11", "Research scholars may borrow up to 8 books for 30 days")], "sufficient", "answer")add("A29", A, "Which grade is awarded for marks between 80 and 89?", "Grade A+ (grade point 9).", ["a+"], [("D13", "Grade A+ (grade point 9): 80 to 89 marks")], "sufficient", "answer")add("A30", A, "What minimum mark is needed in the end-semester examination to pass a course?", "At least 35% in the end-semester examination (21 out of 60).", ["35%|21 out of 60"], [("D13", "at least 35% in the end-semester examination (21 out of 60)")], "sufficient", "answer")
# ----------------------------------------------------------------- multi-passage (20)M = "multi_passage"add("M01", M, "What minimum internal assessment marks are needed for exam eligibility, and how many marks is each internal test worth?", "At least 16 out of 40 IA marks (40%); each internal test is worth 15 marks.", ["16", "15 marks"], [("D03", "that is, at least 16 out of 40"), ("D04", "Internal Test 1 (15 marks)")], "sufficient", "answer")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?", "1-5 September 2025; submit a medical certificate within 3 working days to take one make-up test.", ["1 september 2025", "3 working days"], [("D14", "Internal Test 1: 1 September 2025 to 5 September 2025"), ("D04", "medical certificate is submitted within 3 working days of the missed test")], "sufficient", "answer")add("M03", M, "What happens to a student whose attendance is still short after condonation, and to whom can an eligibility decision be appealed?", "They are marked NE (Not Eligible) and must re-register; appeals go to the Controller of Examinations within 3 working days.", ["not eligible", "controller of examinations"], [("D01", "will be marked NE"), ("D03", "may appeal against an eligibility decision")], "sufficient", "answer")add("M04", M, "Does approved medical leave count as attendance, and for how many days can a Head of Department approve medical leave?", "No, it does not count as attendance (only for condonation); up to 15 days per semester.", ["15 days", "condonation"], [("D10", "Medical leave of up to 15 days"), ("D10", "Approved medical leave does not count as attendance")], "sufficient", "answer")add("M05", M, "Do library dues affect examination eligibility, and what is charged for a lost library book?", "No, but they must be cleared before results are released; lost books cost twice the current price.", ["results", "twice"], [("D03", "Library dues do not affect examination eligibility"), ("D11", "paid for at twice the current price")], "sufficient", "answer")add("M06", M, "What CGPA is needed for First Class with Distinction, and what CGPA earns a 50% merit tuition waiver?", "8.0 or above for First Class with Distinction; 9.0 or above for a 50% waiver.", ["8.0", "9.0"], [("D13", "First Class with Distinction is awarded for a CGPA of 8.0 or above"), ("D07", "CGPA of 9.0 or above in the previous academic year receive a 50% tuition fee waiver")], "sufficient", "answer")add("M07", M, "Can reference books be borrowed, and how many times can a borrowed book be renewed?", "Reference books cannot be borrowed; a borrowed book can be renewed once if not reserved.", ["cannot", "once"], [("D11", "Reference books cannot be borrowed"), ("D11", "may be renewed once")], "sufficient", "answer")add("M08", M, "How many internal assessment marks are given for assignments, and in what file format must assignments be submitted?", "5 marks; as a single PDF file (max 10 MB).", ["5 marks", "pdf"], [("D04", "Assignment (5 marks)"), ("D05", "single PDF file of no more than 10 MB")], "sufficient", "answer")add("M09", M, "When does odd semester course registration close, and what is the last date for late registration?", "Closes 15 July 2025; late registration until 22 July 2025.", ["15 july 2025", "22 july 2025"], [("D09", "closes on 15 July 2025"), ("D09", "permitted until 22 July 2025")], "sufficient", "answer")add("M10", M, "When do odd semester classes begin and what is the last working day of the odd semester?", "Classes begin 21 July 2025; last working day 21 November 2025.", ["21 july 2025", "21 november 2025"], [("D14", "classes begin on 21 July 2025"), ("D14", "Last working day of the odd semester: 21 November 2025")], "sufficient", "answer")add("M11", M, "What documents must be submitted for the need-based scholarship, and how recent must the income certificate be?", "An income certificate from a competent authority issued within the last 6 months, and the previous year's marks card.", ["6 months", "marks card"], [("D07", "within the last 6 months and the marks card of the previous year")], "sufficient", "answer")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?", "Only the higher-value scholarship; renewal needs a CGPA of at least 8.0 and no disciplinary action.", ["higher-value", "8.0"], [("D07", "the higher-value scholarship is awarded"), ("D07", "renewed annually subject to a CGPA of at least 8.0")], "sufficient", "answer")add("M13", M, "How long is each internal test and in which weeks of the semester are they conducted?", "60 minutes; in the 7th and 13th weeks.", ["60 minutes", "7th", "13th"], [("D04", "conducted in the 7th and 13th weeks of the semester")], "sufficient", "answer")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?", "Within 10 working days; review requests within 5 working days of publication.", ["10 working days", "5 working days"], [("D04", "within 10 working days of each test"), ("D04", "within 5 working days of publication")], "sufficient", "answer")add("M15", M, "How long an extension can an instructor grant for an assignment, and what happens if the similarity index is above 20%?", "Up to 5 days if requested before the deadline; similarity above 20% requires resubmission within 3 days.", ["5 days", "resubmission"], [("D05", "Extensions of up to 5 days"), ("D05", "A similarity index above 20% requires resubmission within 3 days")], "sufficient", "answer")add("M16", M, "Which MSc Data Science Semester 3 examination is held in the afternoon session, and what are the afternoon session timings?", "MDS305 Security for Data Science on 10 December 2025; 2:00 PM to 5:00 PM.", ["security for data science|mds305", "2:00 pm"], [("D06", "MDS305 Security for Data Science - Afternoon session"), ("D06", "Afternoon session: 2:00 PM to 5:00 PM")], "sufficient", "answer")add("M17", M, "When are supplementary examinations held, and what is the maximum grade that can be awarded in them?", "In June and July; the maximum grade is A.", ["june", "grade a"], [("D13", "Supplementary examinations are held in June and July")], "sufficient", "answer")add("M18", M, "How many backlog courses prevent promotion to the next year, and when can backlogs be cleared through supplementary examinations?", "More than 4 backlog courses; supplementary exams are held in June and July.", ["4 backlog", "june"], [("D13", "more than 4 backlog courses"), ("D13", "Supplementary examinations are held in June and July")], "sufficient", "answer")add("M19", M, "How is participation in university-approved events treated for attendance, and who must approve it?", "Counted as present for up to 10 contact hours per semester with prior approval of the Head of Department.", ["10 contact hours", "head of department"], [("D01", "counted as present for up to 10 contact hours")], "sufficient", "answer")add("M20", M, "A student returning from academic leave must re-register within which window, and what are the regular odd semester registration dates?", "Within the regular registration window: 1 July 2025 to 15 July 2025.", ["1 july 2025", "15 july 2025"], [("D10", "must re-register within the regular registration window"), ("D09", "opens on 1 July 2025 and closes on 15 July 2025")], "sufficient", "answer")
# ----------------------------------------------------------------- missing (15)N = "missing"missing = [ "What is the fee for revaluation of answer scripts?", "Who is the current Vice-Chancellor of Aranya Valley University?", "What is the annual hostel fee for PhD students?", "Does the university offer a sports quota scholarship?", "What is the dress code during end-semester examinations?", "Can students take the end-semester examinations online from home?", "What minimum CGPA is required to sit for campus placements?", "How many total credits are required to graduate from the MSc Data Science programme?", "What is the fee for a duplicate hall ticket?", "On what date will the 2026 convocation ceremony be held?", "What is the university policy on using generative AI tools such as ChatGPT in assignments?", "What is the parking fee for students' two-wheelers on campus?", "What is the late fine for paying tuition fees after the due date?", "Does the university offer a tuition fee concession for siblings?", "What is the timetable for the even semester examinations in May 2026?",]for i, q in enumerate(missing, 1): add(f"N{i:02d}", N, q, "The documents do not contain this information; the system should abstain.", [], [], "insufficient", "abstain")
# ----------------------------------------------------------------- misleading / irrelevant context (15)I = "misleading"add("I01", I, "Given that internal assessment carries 50 marks, how many marks does the end-semester examination carry?", "The premise is wrong: IA carries 40 marks and the end-semester examination carries 60 marks.", ["40 marks", "60 marks"], [("D04", "40 marks for internal assessment")], "sufficient", "correct_premise")add("I02", I, "Since PG students can register for up to 30 credits, what is the minimum number of credits?", "The maximum is 26, not 30; the minimum is 18.", ["18", "26"], [("D09", "minimum of 18 and a maximum of 26 credits per semester")], "sufficient", "correct_premise")add("I03", I, "As research scholars can borrow 10 books, what is their loan period?", "Research scholars may borrow up to 8 books (not 10) for 30 days.", ["8 books", "30 days"], [("D11", "Research scholars may borrow up to 8 books for 30 days")], "sufficient", "correct_premise")add("I04", I, "Since a CGPA of 8.0 earns a 50% merit tuition waiver, what does a CGPA of 9.0 earn?", "The 50% waiver requires a CGPA of 9.0 or above; 8.5-8.99 earns 25%.", ["9.0", "50%"], [("D07", "CGPA of 9.0 or above in the previous academic year receive a 50% tuition fee waiver")], "sufficient", "correct_premise")add("I05", I, "Given that academic leave can be taken for up to four semesters, how early must a student apply?", "Academic leave is limited to two semesters; apply at least 30 days before the semester.", ["two semesters", "30 days"], [("D10", "maximum of two semesters"), ("D10", "at least 30 days before the start of the semester")], "sufficient", "correct_premise")add("I06", I, "As the MDS301 Deep Learning exam is in the afternoon session, what time does it start?", "It is in the morning session (01 December 2025), which starts at 10:00 AM.", ["10:00 am"], [("D06", "MDS301 Deep Learning - Morning session"), ("D06", "Morning session: 10:00 AM to 1:00 PM")], "sufficient", "correct_premise")add("I07", I, "Since make-up internal tests are allowed for any reason, how many can a student take per semester?", "Make-up tests are only for medical grounds; one make-up test per semester.", ["one make-up test", "medical"], [("D04", "may take one make-up test per semester")], "sufficient", "correct_premise")add("I08", I, "What is the late fee for course registration?", "INR 2,000 (not the INR 500 hostel fine).", ["2000"], [("D09", "with a late fee of INR 2,000")], "sufficient", "answer")add("I09", I, "Above what similarity percentage must an assignment be resubmitted?", "Above 20%.", ["20%"], [("D05", "A similarity index above 20% requires resubmission within 3 days")], "sufficient", "answer")add("I10", I, "At what time does the Central Library close on working days?", "10:00 PM.", ["10:00 pm"], [("D11", "from 8:00 AM to 10:00 PM on working days")], "sufficient", "answer")add("I11", I, "How many days before the examinations is the attendance shortage list published?", "7 days before the commencement of end-semester examinations.", ["7 days"], [("D01", "published 7 days before the commencement of end-semester examinations")], "sufficient", "answer")add("I12", I, "How many contact hours of approved event participation can be counted as present?", "Up to 10 contact hours per semester.", ["10 contact hours"], [("D01", "counted as present for up to 10 contact hours")], "sufficient", "answer")add("I13", I, "What is the minimum CGPA for First Class (without distinction)?", "6.5 (First Class is CGPA 6.5 to 7.99).", ["6.5"], [("D13", "First Class is awarded for a CGPA from 6.5 to 7.99")], "sufficient", "answer")add("I14", I, "For how many days can a course instructor extend an assignment deadline?", "Up to 5 days.", ["5 days"], [("D05", "Extensions of up to 5 days")], "sufficient", "answer")add("I15", I, "Is a calculator with programmable memory allowed in the examination hall?", "No - only non-programmable scientific calculators are permitted.", ["non-programmable"], [("D06", "Only non-programmable scientific calculators are permitted")], "sufficient", "answer")
# ----------------------------------------------------------------- conflicting (20)C = "conflicting"add("C01", C, "What is the minimum attendance required to appear for end-semester examinations?", "Conflict: Attendance Regulations 2023 say 75%; Circular 2025/014 revises it to 80% from 2025-26 (supersedes).", ["75%", "80%"], [("D01", "minimum of 75% attendance"), ("D02", "revised to 80%")], "conflicting", "flag_conflict")add("C02", C, "Up to what percentage can an attendance shortage be condoned on medical grounds?", "Conflict: 10% under the 2023 regulations; limited to 5% by the 2025 circular.", ["10%", "5%"], [("D01", "shortage of attendance of up to 10%"), ("D02", "limited to 5%")], "conflicting", "flag_conflict")add("C03", C, "What is the condonation fee per course for attendance shortage?", "Conflict: INR 500 (2023 regulations) vs INR 1,000 (2025 circular).", ["500", "1000"], [("D01", "condonation fee of INR 500 per course"), ("D02", "revised to INR 1,000 per course")], "conflicting", "flag_conflict")add("C04", C, "According to the examination eligibility rules, what attendance is needed in a course to sit its end-semester exam?", "Conflict: the eligibility rules (2024) state 75%, but the 2025 circular raises the requirement to 80%.", ["75%", "80%"], [("D03", "attendance requirement of 75%"), ("D02", "revised to 80%")], "conflicting", "flag_conflict")add("C05", C, "What is the last date to apply for a scholarship for 2025-26?", "Conflict: 31 August 2025 (policy) vs extended to 15 September 2025 (notice).", ["31 august 2025", "15 september 2025"], [("D07", "by 31 August 2025"), ("D08", "extended to 15 September 2025")], "conflicting", "flag_conflict")add("C06", C, "What is the family income limit for the need-based scholarship?", "Conflict: INR 6,00,000 (policy) vs INR 8,00,000 (revised notice).", ["600000", "800000"], [("D07", "does not exceed INR 6,00,000"), ("D08", "revised to INR 8,00,000")], "conflicting", "flag_conflict")add("C07", C, "Are late assignment submissions accepted?", "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.", ["10%", "not be accepted"], [("D05", "Late submissions are accepted for up to 3 calendar days"), ("D04", "will not be accepted for internal assessment")], "conflicting", "flag_conflict")add("C08", C, "What is the penalty for submitting an assignment one day late?", "Conflict: 10% of maximum marks per day (Assignment Policy) vs not accepted at all (IA Guidelines).", ["10%", "not be accepted"], [("D05", "penalty of 10% of the maximum marks per day"), ("D04", "will not be accepted for internal assessment")], "conflicting", "flag_conflict")add("C09", C, "How many books can a postgraduate student borrow from the library?", "Conflict: 5 books (2023 regulations) vs 6 books from 1 August 2025 (notice).", ["5 books", "6 books"], [("D11", "Postgraduate students may borrow up to 5 books"), ("D12", "may borrow up to 6 books")], "conflicting", "flag_conflict")add("C10", C, "For how many days can a postgraduate student keep a borrowed library book?", "Conflict: 14 days (2023) vs 21 days (2025 notice).", ["14 days", "21 days"], [("D11", "Postgraduate students may borrow up to 5 books for 14 days"), ("D12", "for a period of 21 days")], "conflicting", "flag_conflict")add("C11", C, "What is the library overdue fine per book per day?", "Conflict: INR 5 (2023) vs INR 10 (2025 notice).", ["inr 5 ", "inr 10 "], [("D11", "overdue fine of INR 5 per book per day"), ("D12", "revised to INR 10 per book per day")], "conflicting", "flag_conflict")add("C12", C, "How long is the add/drop period for elective courses?", "Conflict: 10 working days (Registration Guidelines) vs 7 working days (Academic Calendar).", ["10 working days", "7 working days"], [("D09", "within 10 working days from the start of classes"), ("D14", "7 working days from the start of classes")], "conflicting", "flag_conflict")add("C13", C, "What minimum aggregate percentage is needed to pass a postgraduate course?", "Conflict: 40% (Grading Policy) vs 50% for PG courses (PG Handbook).", ["40%", "50%"], [("D13", "at least 40% marks in aggregate"), ("D15", "at least 50% marks in aggregate")], "conflicting", "flag_conflict")add("C14", C, "On what date do the odd semester end-semester examinations begin?", "Conflict: 1 December 2025 (Timetable, Oct 2025) vs 3 December 2025 (Academic Calendar, June 2025).", ["1 december 2025", "3 december 2025"], [("D06", "commence on 1 December 2025"), ("D14", "End-semester examinations: from 3 December 2025")], "conflicting", "flag_conflict")add("C15", C, "Can I drop an elective course 9 working days after classes start?", "Conflict: allowed under the Registration Guidelines (10 working days) but not under the Academic Calendar (7 working days).", ["10 working days", "7 working days"], [("D09", "within 10 working days from the start of classes"), ("D14", "7 working days from the start of classes")], "conflicting", "flag_conflict")add("C16", C, "If my attendance in a course is 78%, am I eligible for the end-semester examination?", "Conflict: eligible under the 2023 rule (75%), but below the 80% minimum under the 2025 circular (condonable between 75% and 80%).", ["75%", "80%"], [("D01", "minimum of 75% attendance"), ("D02", "revised to 80%")], "conflicting", "flag_conflict")add("C17", C, "If a PG student scores 45% in aggregate in a course, do they pass?", "Conflict: pass under the Grading Policy (40%), fail under the PG Handbook (50%).", ["40%", "50%"], [("D13", "at least 40% marks in aggregate"), ("D15", "at least 50% marks in aggregate")], "conflicting", "flag_conflict")add("C18", C, "What is the lowest attendance percentage that can be condoned on medical grounds?", "Conflict: 65% under the 2023 regulations vs 75% under the 2025 circular.", ["65%", "75%"], [("D01", "attendance between 65% and 75%"), ("D02", "attendance between 75% and 80%")], "conflicting", "flag_conflict")add("C19", C, "Which attendance rule is the latest, and what minimum attendance does it require?", "Conflict: the 2025 circular (latest) requires 80%, superseding the 75% of the 2023 regulations.", ["80%", "75%"], [("D02", "revised to 80%"), ("D01", "minimum of 75% attendance")], "conflicting", "flag_conflict")add("C20", C, "According to the academic calendar, what is the scholarship application deadline, and has it changed?", "Conflict: the calendar says 31 August 2025, but the notice extends it to 15 September 2025.", ["31 august 2025", "15 september 2025"], [("D14", "Last date for scholarship applications: 31 August 2025"), ("D08", "extended to 15 September 2025")], "conflicting", "flag_conflict")
assert len(Q) == 100, len(Q)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139// Renders reports/report_model.json (built by build_report.py) into a Word document with docx-js.// Usage: node scripts/render_report_docx.js reports/report_model.json reports/project_report.docxconst fs = require("fs");const path = require("path");const { Document, Packer, Paragraph, TextRun, HeadingLevel, AlignmentType, Table, TableRow, TableCell, WidthType, ShadingType, ImageRun, PageBreak, LevelFormat, Footer, Header, PageNumber, TableOfContents, BorderStyle,} = require("docx");
const [, , inPath, outPath] = process.argv;const blocks = JSON.parse(fs.readFileSync(inPath, "utf8"));const FONT = "Calibri";const CM = 567; // DXA per cmconst CONTENT_W = 16 * CM; // A4 21 cm - 2 x 2.5 cm margins
function pngSize(file) { const b = fs.readFileSync(file); return { w: b.readUInt32BE(16), h: b.readUInt32BE(20), data: b };}
const children = [];const numberRefs = [];const h1Titles = blocks.filter(x => x.t === "h1").map(x => x.text);for (const b of blocks) { switch (b.t) { case "title": children.push(new Paragraph({ spacing: { before: 2400, after: 240 }, alignment: AlignmentType.CENTER, children: [new TextRun({ text: b.title, font: FONT, size: 56, bold: true, color: "1C5CAB" })] })); children.push(new Paragraph({ spacing: { after: 960 }, alignment: AlignmentType.CENTER, children: [new TextRun({ text: b.subtitle, font: FONT, size: 30 })] })); for (const l of b.lines) children.push(new Paragraph({ alignment: AlignmentType.CENTER, spacing: { after: 160 }, children: [new TextRun({ text: l, font: FONT, size: 24 })] })); children.push(new Paragraph({ alignment: AlignmentType.CENTER, spacing: { before: 1200 }, children: [new TextRun({ text: "All documents and data in this project are SYNTHETIC DEMONSTRATION DATA describing a fictional university.", font: FONT, size: 20, italics: true, color: "B00020" })] })); children.push(new Paragraph({ children: [new PageBreak()] })); children.push(new Paragraph({ spacing: { after: 240 }, children: [new TextRun({ text: "Contents", font: FONT, size: 32, bold: true, color: "1C5CAB" })] })); for (const t of h1Titles) children.push(new Paragraph({ spacing: { after: 90 }, indent: { left: t.match(/^\d/) ? 0 : 0 }, children: [new TextRun({ text: t, font: FONT, size: 23 })] })); break; case "h1": children.push(new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun(b.text)] })); break; case "h2": children.push(new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun(b.text)] })); break; case "p": children.push(new Paragraph({ alignment: AlignmentType.JUSTIFIED, spacing: { after: 140, line: 300 }, children: [new TextRun({ text: b.text, font: FONT, size: 22 })] })); break; case "caption": children.push(new Paragraph({ alignment: AlignmentType.CENTER, spacing: { before: 60, after: 220 }, children: [new TextRun({ text: b.text, font: FONT, size: 18, italics: true, color: "52514E" })] })); break; case "bullets": case "numbers": { const ref = b.t === "bullets" ? "bul" : `num${numberRefs.length}`; if (b.t === "numbers") numberRefs.push(ref); for (const it of b.items) children.push(new Paragraph({ numbering: { reference: ref, level: 0 }, spacing: { after: 80, line: 290 }, children: [new TextRun({ text: it, font: FONT, size: 22 })] })); break; } case "refs": b.items.forEach((r, i) => children.push(new Paragraph({ spacing: { after: 100 }, indent: { left: 567, hanging: 567 }, children: [new TextRun({ text: `[${i + 1}]\t${r}`, font: FONT, size: 20 })] }))); break; case "code": for (const line of b.text.split("\n")) children.push(new Paragraph({ spacing: { after: 0 }, shading: { fill: "F4F6F8", type: ShadingType.CLEAR, color: "auto" }, children: [new TextRun({ text: line, font: "Consolas", size: 18 })] })); break; case "pagebreak": children.push(new Paragraph({ children: [new PageBreak()] })); break; case "img": { if (!fs.existsSync(b.path)) break; const s = pngSize(b.path); const wPx = Math.round(b.width_cm * 37.8); let hPx = Math.round(wPx * s.h / s.w); const maxH = 22 * 37.8; let w = wPx; if (hPx > maxH) { w = Math.round(wPx * maxH / hPx); hPx = Math.round(maxH); } children.push(new Paragraph({ alignment: AlignmentType.CENTER, spacing: { before: 120 }, children: [new ImageRun({ type: "png", data: s.data, transformation: { width: w, height: hPx }, altText: { title: path.basename(b.path), description: b.caption || path.basename(b.path), name: path.basename(b.path) } })] })); break; } case "table": { const n = b.header.length; let widths = b.widths || Array(n).fill(16 / n); const tot = widths.reduce((a, c) => a + c, 0); const dx = widths.map(x => Math.floor(x / tot * CONTENT_W)); dx[dx.length - 1] += CONTENT_W - dx.reduce((a, c) => a + c, 0); const sz = Math.round((b.size || 8) * 2); const border = { style: BorderStyle.SINGLE, size: 4, color: "BFBFBF" }; const borders = { top: border, bottom: border, left: border, right: border }; const mkCell = (text, i, head) => new TableCell({ width: { size: dx[i], type: WidthType.DXA }, borders, shading: head ? { fill: "DCE8F7", type: ShadingType.CLEAR, color: "auto" } : undefined, margins: { top: 40, bottom: 40, left: 70, right: 70 }, children: [new Paragraph({ children: [new TextRun({ text: String(text), font: FONT, size: sz, bold: head })] })], }); const rows = [new TableRow({ tableHeader: true, children: b.header.map((h, i) => mkCell(h, i, true)) })]; for (const r of b.rows) rows.push(new TableRow({ cantSplit: true, children: r.map((c, i) => mkCell(c, i, false)) })); children.push(new Table({ width: { size: CONTENT_W, type: WidthType.DXA }, columnWidths: dx, rows })); break; } }}
const numberingConfig = [{ reference: "bul", levels: [{ level: 0, format: LevelFormat.BULLET, text: "•", alignment: AlignmentType.LEFT, style: { paragraph: { indent: { left: 567, hanging: 283 } } } }] }];for (const ref of numberRefs) numberingConfig.push({ reference: ref, levels: [{ level: 0, format: LevelFormat.DECIMAL, text: "%1.", alignment: AlignmentType.LEFT, style: { paragraph: { indent: { left: 567, hanging: 340 } } } }] });
const doc = new Document({ creator: "EvidenceGuard AI report builder", title: "EvidenceGuard AI - MSc Project Report", features: { updateFields: true }, styles: { default: { document: { run: { font: FONT, size: 22 } } }, paragraphStyles: [ { id: "Heading1", name: "Heading 1", basedOn: "Normal", next: "Normal", quickFormat: true, run: { font: FONT, size: 32, bold: true, color: "1C5CAB" }, paragraph: { spacing: { before: 360, after: 160 }, keepNext: true, outlineLevel: 0 } }, { id: "Heading2", name: "Heading 2", basedOn: "Normal", next: "Normal", quickFormat: true, run: { font: FONT, size: 26, bold: true, color: "0B0B0B" }, paragraph: { spacing: { before: 240, after: 120 }, keepNext: true, outlineLevel: 1 } }, ], }, numbering: { config: numberingConfig }, sections: [{ properties: { page: { size: { width: 11906, height: 16838 }, margin: { top: 1418, bottom: 1418, left: 1418, right: 1418 } } }, headers: { default: new Header({ children: [new Paragraph({ alignment: AlignmentType.RIGHT, children: [new TextRun({ text: "EvidenceGuard AI - MSc Project Report (synthetic data)", font: FONT, size: 16, color: "8A8986" })] })] }) }, footers: { default: new Footer({ children: [new Paragraph({ alignment: AlignmentType.CENTER, children: [new TextRun({ children: ["Page ", PageNumber.CURRENT, " of ", PageNumber.TOTAL_PAGES], font: FONT, size: 18 })] })] }) }, children, }],});
Packer.toBuffer(doc).then(buf => { fs.writeFileSync(outPath, buf); console.log("docx written", outPath); });123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316"""Runs the complete experimental evaluation of EvidenceGuard AI.
Steps 1. Stratified DEV/TEST split of the 100 questions (30% per category, rounded: 29 dev / 71 test, seed 42). 2. Threshold calibration of the verifier on the DEV split only (grid search, objective = behaviour accuracy of the complete system). Saved to results/calibrated_thresholds.json. 3. Runs the 4 configurations on all 100 questions: 1. Baseline RAG 2. RAG + hybrid retrieval & reranking 3. RAG + evidence verification 4. EvidenceGuard (complete) 4. Writes metrics (all / test / dev), per-question results, category breakdown, error analysis and failure cases to results/, and charts to results/charts/.
Usage: python scripts/run_evaluation.py # auto backend python scripts/run_evaluation.py --backend lite # fully offline components python scripts/run_evaluation.py --backend full --llm hf_api # HF models + HF Inference API"""from __future__ import annotations
import argparseimport csvimport itertoolsimport jsonimport platformimport randomimport sysimport timefrom collections import Counter, defaultdictfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT))
import config # noqa: E402from src.evaluation import aggregate, by_category, classify_error, score_question # noqa: E402from src.text_utils import normalize # noqa: E402
RES = config.RESULTS_DIRCH = config.CHARTS_DIRORDER = ["baseline", "rerank", "verify", "full"]SHORT = {"baseline": "Baseline RAG", "rerank": "+ Reranking", "verify": "+ Verification", "full": "EvidenceGuard"}COLORS = {"baseline": "#2a78d6", "rerank": "#eb6834", "verify": "#1baf7a", "full": "#eda100"} # validated palette
def split(questions, dev_frac=0.3, seed=42): rng = random.Random(seed) by = defaultdict(list) for q in questions: by[q["category"]].append(q["id"]) dev = set() for cat, ids in sorted(by.items()): ids = sorted(ids) rng.shuffle(ids) dev |= set(ids[: round(len(ids) * dev_frac)]) return dev
def relevance_fn_factory(kb, questions): from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity vec = TfidfVectorizer(stop_words="english", sublinear_tf=True).fit( [c.text for c in kb.chunks] + [q["question"] for q in questions])
def f(q, a): return float(cosine_similarity(vec.transform([q]), vec.transform([a]))[0, 0]) return f
def calibrate(system, dev_qs, page_text): """Grid search on DEV only. Two stages: sufficiency/abstention, then conflict sensitivity.""" base = dict(system.verifier.th) pipe = system.pipelines["full"]
def score(th): system.set_thresholds(th) rows = [score_question(q, pipe.answer(q["question"]), page_text) for q in dev_qs] a = aggregate(rows) return a["behaviour_accuracy"], a["abstention_accuracy"], a["unsupported_answer_rate"]
best, best_s = dict(base), (-1, -1, 9) 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]) for rel, cov, conf in grid1: th = dict(base, min_relevance=rel, min_coverage=cov, partial_coverage=max(0.0, cov - 0.1), min_confidence=conf) s = score(th) if (s[0], s[1], -s[2]) > (best_s[0], best_s[1], -best_s[2]): best, best_s = th, s for sc, sim in itertools.product([0.25, 0.3, 0.35, 0.45], [0.25, 0.3, 0.4]): th = dict(best, conflict_sentence_coverage=sc, conflict_topic_sim=sim) s = score(th) if (s[0], s[1], -s[2]) > (best_s[0], best_s[1], -best_s[2]): best, best_s = th, s system.set_thresholds(best) return best, {"dev_behaviour_accuracy": best_s[0], "dev_abstention_accuracy": best_s[1], "dev_unsupported_rate": best_s[2]}
# ------------------------------------------------------------------------------------ chartsdef charts(metrics_all, cat_tables, rows_by_cfg): import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt
plt.rcParams.update({"font.size": 10, "axes.spines.top": False, "axes.spines.right": False, "axes.edgecolor": "#8a8986", "axes.labelcolor": "#0b0b0b", "xtick.color": "#52514e", "ytick.color": "#52514e", "figure.facecolor": "#fcfcfb", "axes.facecolor": "#fcfcfb", "grid.color": "#e6e5e1"})
def grouped(metric_keys, labels, title, fname, ylim=1.0, pct=True): fig, ax = plt.subplots(figsize=(9, 4.2)) n = len(ORDER) width = 0.8 / n for i, cfg in enumerate(ORDER): vals = [metrics_all[cfg][k] if metrics_all[cfg][k] is not None else 0 for k in metric_keys] xs = [j + (i - (n - 1) / 2) * width for j in range(len(metric_keys))] bars = ax.bar(xs, vals, width * 0.92, color=COLORS[cfg], label=SHORT[cfg], zorder=3) for b, v in zip(bars, vals): ax.text(b.get_x() + b.get_width() / 2, b.get_height() + ylim * 0.012, f"{v:.2f}" if pct else f"{v:.3f}", ha="center", va="bottom", fontsize=7.5, color="#52514e") ax.set_xticks(range(len(metric_keys)), labels) ax.set_ylim(0, ylim * 1.12) ax.grid(axis="y", zorder=0) ax.set_title(title, loc="left", fontsize=12, color="#0b0b0b") ax.legend(frameon=False, ncol=4, loc="upper left", bbox_to_anchor=(0, -0.12)) fig.tight_layout() fig.savefig(CH / fname, dpi=150) plt.close(fig)
grouped(["precision_at_k", "recall_at_k", "mrr", "context_precision", "context_recall"], ["Precision@5", "Recall@5", "MRR", "Context precision", "Context recall"], "Retrieval quality (all 100 questions)", "retrieval_comparison.png") grouped(["answer_correctness", "behaviour_accuracy", "faithfulness", "grounded_faithfulness", "answer_relevance"], ["Answer correctness", "Behaviour accuracy", "Faithfulness\n(to context)", "Evidence-grounded\nfaithfulness", "Answer relevance\n(lexical proxy)"], "Answer quality (all 100 questions)", "answer_quality_comparison.png") grouped(["unsupported_answer_rate", "abstention_accuracy", "abstention_f1", "contradiction_f1", "citation_support_accuracy"], ["Unsupported answer\nrate (lower = better)", "Abstention\naccuracy", "Abstention F1", "Contradiction\ndetection F1", "Citation support\naccuracy"], "Reliability (all 100 questions)", "reliability_comparison.png") tmax = max(metrics_all[c]["avg_response_time_s"] for c in ORDER) grouped(["avg_response_time_s", "avg_retrieval_time_s", "avg_verification_time_s", "avg_generation_time_s"], ["Total", "Retrieval + rerank", "Verification", "Generation"], "Average time per question (seconds)", "response_time.png", ylim=tmax, pct=False)
# behaviour accuracy by category cats = ["answerable", "multi_passage", "misleading", "conflicting", "missing"] fig, ax = plt.subplots(figsize=(9, 4.2)) width = 0.2 for i, cfg in enumerate(ORDER): vals = [cat_tables[cfg][c]["behaviour_accuracy"] for c in cats] xs = [j + (i - 1.5) * width for j in range(len(cats))] bars = ax.bar(xs, vals, width * 0.92, color=COLORS[cfg], label=SHORT[cfg], zorder=3) for b, v in zip(bars, vals): ax.text(b.get_x() + b.get_width() / 2, b.get_height() + 0.012, f"{v:.2f}", ha="center", va="bottom", fontsize=7.5, color="#52514e") ax.set_xticks(range(len(cats)), ["Answerable\n(30)", "Multi-passage\n(20)", "Misleading\n(15)", "Conflicting\n(20)", "Missing info\n(15)"]) ax.set_ylim(0, 1.12) ax.grid(axis="y", zorder=0) ax.set_title("Expected-behaviour accuracy by question category", loc="left", fontsize=12) ax.legend(frameon=False, ncol=4, loc="upper left", bbox_to_anchor=(0, -0.14)) fig.tight_layout() fig.savefig(CH / "category_breakdown.png", dpi=150) plt.close(fig)
# error taxonomy for baseline vs full fig, axes = plt.subplots(1, 2, figsize=(10, 3.8), sharex=True) kinds = ["answered unanswerable question (hallucination risk)", "missed conflict", "over-abstention (answer was available)", "incomplete answer (some key facts missing)", "wrong/irrelevant answer content", "retrieval failure (no gold page retrieved)"] short = ["Answered unanswerable", "Missed conflict", "Over-abstention", "Incomplete answer", "Wrong content", "Retrieval failure"] mx = 0 counts = {} for cfg in ("baseline", "full"): c = Counter(classify_error(r) for r in rows_by_cfg[cfg]) counts[cfg] = [c.get(k, 0) for k in kinds] mx = max(mx, max(counts[cfg])) for ax, cfg in zip(axes, ("baseline", "full")): bars = ax.barh(short[::-1], counts[cfg][::-1], color=COLORS[cfg], zorder=3, height=0.6) for b, v in zip(bars, counts[cfg][::-1]): ax.text(v + mx * 0.02, b.get_y() + b.get_height() / 2, str(v), va="center", fontsize=8, color="#52514e") ax.set_title(f"{SHORT[cfg]} - errors ({sum(counts[cfg])})", loc="left", fontsize=11) ax.grid(axis="x", zorder=0) ax.set_xlim(0, mx * 1.2 + 1) fig.tight_layout() fig.savefig(CH / "error_analysis.png", dpi=150) plt.close(fig)
# ------------------------------------------------------------------------------------ maindef main(): ap = argparse.ArgumentParser() ap.add_argument("--backend", default=config.EG_BACKEND, choices=["auto", "full", "lite"]) ap.add_argument("--llm", default=config.LLM_BACKEND, choices=["auto", "hf_api", "local", "extractive"]) ap.add_argument("--no-calibrate", action="store_true") args = ap.parse_args()
from src.system import EvidenceGuardSystem questions = json.loads(config.EVAL_DATA_PATH.read_text()) import os os.environ["EG_IGNORE_CALIBRATION"] = "1" # start from defaults; calibrate fresh t0 = time.time() system = EvidenceGuardSystem(args.backend, args.llm, thresholds=dict(config.THRESHOLDS)) print("Components:", json.dumps(system.component_names(), indent=1)) page_text = {(d, i + 1): normalize(t) for d, info in system.kb.docs.items() for i, t in enumerate(info.page_texts)} rel_fn = relevance_fn_factory(system.kb, questions)
dev_ids = split(questions) dev_qs = [q for q in questions if q["id"] in dev_ids] if not args.no_calibrate: th, dev_scores = calibrate(system, dev_qs, page_text) (RES / "calibrated_thresholds.json").write_text(json.dumps( {"backend": system.effective_backend, "thresholds": th, "dev_ids": sorted(dev_ids), **dev_scores}, indent=2)) print("Calibrated on DEV:", dev_scores)
rows_by_cfg, per_q = {}, [] for cfg in ORDER: rows = [] for q in questions: r = system.pipelines[cfg].answer(q["question"]) row = score_question(q, r, page_text, rel_fn) row["config"] = cfg row["split"] = "dev" if q["id"] in dev_ids else "test" row["error_type"] = classify_error(row) rows.append(row) rows_by_cfg[cfg] = rows per_q += rows print(f"{cfg:9s} done")
metrics = {"all": {}, "test": {}, "dev": {}} cats = {} for cfg in ORDER: rows = rows_by_cfg[cfg] metrics["all"][cfg] = aggregate(rows) metrics["test"][cfg] = aggregate([r for r in rows if r["split"] == "test"]) metrics["dev"][cfg] = aggregate([r for r in rows if r["split"] == "dev"]) cats[cfg] = by_category(rows)
meta = { "note": "Experiments use SYNTHETIC documents of a fictional university. Results do not establish " "real-world university policy accuracy.", "components": system.component_names(), "backend": args.backend, "llm_backend": args.llm, "thresholds": system.verifier.th, "n_questions": len(questions), "dev_questions": len(dev_ids), "test_questions": len(questions) - len(dev_ids), "python": platform.python_version(), "machine": platform.machine(), "cpu_count": os.cpu_count(), "runtime_s": round(time.time() - t0, 1), "date": time.strftime("%Y-%m-%d %H:%M"), } (RES / "metrics.json").write_text(json.dumps( {"meta": meta, "metrics": metrics, "by_category": cats, "config_names": SHORT}, indent=2))
keys = list(metrics["all"]["full"].keys()) with open(RES / "metrics.csv", "w", newline="") as f: w = csv.writer(f) w.writerow(["split", "configuration"] + keys) for sp in ("all", "test", "dev"): for cfg in ORDER: w.writerow([sp, SHORT[cfg]] + [metrics[sp][cfg][k] for k in keys]) with open(RES / "category_breakdown.csv", "w", newline="") as f: w = csv.writer(f) w.writerow(["configuration", "category", "n", "answer_correctness", "behaviour_accuracy", "unsupported_rate", "abstention_rate"]) for cfg in ORDER: for c, v in cats[cfg].items(): w.writerow([SHORT[cfg], c, v["n"], v["answer_correctness"], v["behaviour_accuracy"], v["unsupported_rate"], v["abstention_rate"]]) fields = ["config", "split", "id", "category", "question", "expected_behaviour", "decision", "abstained", "conflict_flagged", "correct", "behaviour_ok", "unsupported", "error_type", "keywords_hit", "keywords_total", "precision_at_k", "recall_at_k", "mrr", "faithfulness", "grounded_faithfulness", "citation_support", "confidence", "t_total", "answer", "expected_answer", "explanation", "retrieved"] with open(RES / "per_question_results.csv", "w", newline="") as f: w = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore") w.writeheader() w.writerows(per_q)
# error analysis + failure cases err = {cfg: Counter(r["error_type"] for r in rows_by_cfg[cfg]) for cfg in ORDER} with open(RES / "error_analysis.csv", "w", newline="") as f: w = csv.writer(f) types = sorted({t for c in err.values() for t in c}) w.writerow(["error_type"] + [SHORT[c] for c in ORDER]) for t in types: w.writerow([t] + [err[c].get(t, 0) for c in ORDER]) fails = [] for r in rows_by_cfg["full"]: if not r["behaviour_ok"]: b = next(x for x in rows_by_cfg["baseline"] if x["id"] == r["id"]) fails.append({k: r[k] for k in ("id", "category", "question", "expected_behaviour", "error_type", "decision", "answer", "expected_answer", "explanation", "retrieved")} | {"baseline_answer": b["answer"], "baseline_ok": b["behaviour_ok"]}) wins = [{"id": r["id"], "category": r["category"], "question": r["question"], "baseline_answer": b["answer"], "evidenceguard_answer": r["answer"], "explanation": r["explanation"]} for r, b in zip(rows_by_cfg["full"], rows_by_cfg["baseline"]) if r["behaviour_ok"] and not b["behaviour_ok"]] (RES / "failure_cases.json").write_text(json.dumps({"evidenceguard_failures": fails, "evidenceguard_fixes_over_baseline": wins}, indent=2)) charts(metrics["all"], cats, rows_by_cfg)
print("\n=== ALL 100 questions ===") show = ["recall_at_k", "mrr", "answer_correctness", "behaviour_accuracy", "grounded_faithfulness", "unsupported_answer_rate", "abstention_accuracy", "contradiction_f1", "citation_support_accuracy", "avg_response_time_s"] print(f"{'config':16s}" + "".join(f"{k[:14]:>15s}" for k in show)) for sp in ("all", "test"): print(f"--- {sp}") for cfg in ORDER: 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)) print("\nErrors:", {SHORT[c]: dict(err[c]) for c in ("baseline", "full")}) print(f"Runtime {meta['runtime_s']} s")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657"""Paired significance tests between configurations (exact McNemar + bootstrap 95% CI).
Reads results/per_question_results.csv and writes results/significance.json."""import csvimport jsonimport randomfrom math import combfrom pathlib import Path
RES = Path(__file__).resolve().parents[1] / "results"
def mcnemar_exact(b, c): n = b + c if n == 0: return 1.0 k = min(b, c) p = sum(comb(n, i) for i in range(k + 1)) / 2 ** n * 2 return min(1.0, p)
def main(): rows = list(csv.DictReader(open(RES / "per_question_results.csv"))) by = {} for r in rows: by.setdefault(r["config"], {})[r["id"]] = r out = {} for metric, field, better_low in (("behaviour_accuracy", "behaviour_ok", False), ("unsupported_answer", "unsupported", True)): for split in ("all", "test"): for other in ("rerank", "verify", "full"): ids = [i for i in by["baseline"] if split == "all" or by["baseline"][i]["split"] == "test"] a = [by["baseline"][i][field] == "True" for i in ids] b = [by[other][i][field] == "True" for i in ids] n01 = sum((not x) and y for x, y in zip(a, b)) # baseline 0, other 1 n10 = sum(x and (not y) for x, y in zip(a, b)) rng = random.Random(0) diffs = [] for _ in range(5000): s = [rng.randrange(len(ids)) for _ in ids] diffs.append(sum(b[j] for j in s) / len(s) - sum(a[j] for j in s) / len(s)) diffs.sort() out[f"{metric}|{split}|baseline_vs_{other}"] = { "n": len(ids), "baseline": round(sum(a) / len(a), 4), other: round(sum(b) / len(b), 4), "difference": round(sum(b) / len(b) - sum(a) / len(a), 4), "ci95": [round(diffs[125], 4), round(diffs[4874], 4)], "only_other_true": n01, "only_baseline_true": n10, "mcnemar_exact_p": round(mcnemar_exact(n01, n10), 6), } (RES / "significance.json").write_text(json.dumps(out, indent=2)) for k, v in out.items(): print(k, v)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960"""SYSTEM A - Baseline RAG: dense retrieval (FAISS) -> LLM answer with source citations. No checks."""from __future__ import annotations
import time
import configfrom src.retrieval import DenseRetriever, HybridRetrieverfrom src.reranker import rerank
def passage_dicts(items): out = [] for i, r in enumerate(items, 1): c = r.chunk out.append({"n": i, "doc_id": c.doc_id, "doc_name": c.doc_name, "title": c.title, "page": c.page, "issued": c.issued, "text": c.text, "dense": round(r.dense, 4), "sparse": round(r.sparse, 4), "rerank": None if r.rerank is None else round(r.rerank, 4), "source": r.source, "relevance": round(r.relevance, 4)}) return out
def render_claims(claims) -> str: return " ".join(f"{s} [{', '.join(map(str, c))}]" if c else s for s, c in claims)
class BaselineRAG: """Standard RAG. Optionally with hybrid retrieval + reranking (ablation 'RAG + reranking')."""
def __init__(self, kb, generator, reranker=None, use_hybrid=False, use_rerank=False, top_k: int = config.TOP_K, name: str = "Baseline RAG"): self.kb, self.gen, self.reranker = kb, generator, reranker self.use_rerank = use_rerank and reranker is not None self.retriever = HybridRetriever(kb) if use_hybrid else DenseRetriever(kb) self.top_k, self.name = top_k, name
def answer(self, question: str) -> dict: t0 = time.perf_counter() n = config.CANDIDATES if self.use_rerank else self.top_k items = self.retriever.retrieve(question, n) t_ret = time.perf_counter() - t0 t1 = time.perf_counter() if self.use_rerank: items = rerank(self.reranker, question, items, self.top_k) t_rr = time.perf_counter() - t1 gen = self.gen.generate(question, items, mode="baseline") text = render_claims(gen.claims) if gen.claims else (gen.text or "No answer generated.") cited = sorted({c for _, cs in gen.claims for c in cs if 1 <= c <= len(items)}) return { "system": self.name, "question": question, "answer": text, "decision": "answered", "claims": gen.claims, "citations": [{"n": c, "doc_name": items[c - 1].chunk.doc_name, "title": items[c - 1].chunk.title, "page": items[c - 1].chunk.page} for c in cited], "passages": passage_dicts(items), "sufficiency": None, "conflicts": [], "citation_checks": [], "confidence": None, "explanation": "Baseline RAG always answers from the top retrieved passages; it performs no " "sufficiency, contradiction or citation checks.", "timings": {"retrieval": t_ret, "rerank": t_rr, "verification": 0.0, "generation": gen.seconds, "total": time.perf_counter() - t0}, "generator": gen.backend, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""PDF ingestion: text extraction, cleaning, metadata detection and sentence-aware chunking."""from __future__ import annotations
import jsonimport refrom dataclasses import asdict, dataclass, fieldfrom pathlib import Path
import configfrom src.text_utils import split_sentences
_BANNER = re.compile(r"SYNTHETIC DEMONSTRATION DATA.*?policy", re.I)_FOOTER = re.compile(r"^[A-Z]{2,}/[A-Z0-9/.-]+\s*\|.*$|^Page \d+ of \d+$", re.I)_DATE_ISO = re.compile(r"\b(20\d{2})-(\d{2})-(\d{2})\b")_DATE_LONG = re.compile(r"\b(\d{1,2})\s+(January|February|March|April|May|June|July|August|September|" r"October|November|December)\s+(20\d{2})\b", re.I)_MONTHS = {m: i for i, m in enumerate(["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"], 1)}
@dataclassclass Chunk: chunk_id: str doc_id: str doc_name: str title: str page: int text: str issued: str = "" # ISO date if known; used to decide which version is newer
def to_dict(self): return asdict(self)
@dataclassclass DocumentInfo: doc_id: str doc_name: str title: str pages: int chunks: int issued: str = "" status: str = "ok" message: str = "" page_texts: list = field(default_factory=list, repr=False)
def extract_pages(path: str | Path) -> list[str]: """Return raw text of every page. PyMuPDF first, pypdf as a fallback.""" return extract_pdf(path)[0]
def extract_pdf(path: str | Path) -> tuple[list[str], str]: """(page texts, metadata title).""" try: import pymupdf with pymupdf.open(str(path)) as pdf: return [p.get_text() for p in pdf], (pdf.metadata or {}).get("title", "") or "" except Exception: from pypdf import PdfReader r = PdfReader(str(path)) title = (r.metadata.title if r.metadata and r.metadata.title else "") or "" return [(p.extract_text() or "") for p in r.pages], title
def clean_page(text: str) -> str: text = _BANNER.sub(" ", text or "") lines = [] for ln in text.splitlines(): s = ln.strip() if not s or _FOOTER.match(s): continue words = re.sub(r"^\d+\.\s*", "", s).split() # Short Title-Case lines without punctuation are headings ("2. Late Submission"): # terminate them so they become their own sentence instead of gluing onto the next one. if (words and len(words) <= 7 and s[-1] not in ".:;,)" and words[0][0].isupper() and all(w[0].isupper() or not w[0].isalpha() for w in words if w.lower() not in {"and", "of", "the", "for", "to", "in", "on", "a", "-"})): s += "." lines.append(s) text = "\n".join(lines) text = re.sub(r"(\w)-\n(\w)", r"\1\2", text) # de-hyphenate line breaks text = re.sub(r"\s*\n\s*", " ", text) return re.sub(r"\s{2,}", " ", text).strip()
def _to_iso(text: str) -> str: m = re.search(r"Issued\s+(20\d{2}-\d{2}-\d{2})", text) if m: return m.group(1) m = _DATE_ISO.search(text) if m: return m.group(0) m = _DATE_LONG.search(text) if m: d, mon, y = m.groups() return f"{y}-{_MONTHS[mon.lower()]:02d}-{int(d):02d}" return ""
def _manifest() -> dict: p = config.SAMPLE_DATA_DIR / "corpus_manifest.json" if p.exists(): return {m["filename"]: m for m in json.loads(p.read_text())} return {}
def chunk_page(sentences: list[str], target_words: int, overlap: int) -> list[str]: chunks, cur, words = [], [], 0 for s in sentences: n = len(s.split()) if cur and words + n > target_words: chunks.append(" ".join(cur)) cur = cur[-overlap:] if overlap else [] words = sum(len(x.split()) for x in cur) cur.append(s) words += n if cur: tail = " ".join(cur) if not chunks or tail not in chunks[-1]: chunks.append(tail) return chunks
def process_pdf(path: str | Path, doc_id: str | None = None, target_words: int | None = None, overlap: int | None = None) -> tuple[DocumentInfo, list[Chunk]]: path = Path(path) target_words = target_words or config.CHUNK_TARGET_WORDS overlap = config.CHUNK_OVERLAP_SENTENCES if overlap is None else overlap doc_id = doc_id or re.sub(r"[^A-Za-z0-9]+", "_", path.stem)[:40] try: raw, meta_title = extract_pdf(path) except Exception as e: # corrupt / encrypted PDF return DocumentInfo(doc_id, path.name, path.stem, 0, 0, status="error", message=str(e)), []
pages = [clean_page(p) for p in raw] meta = _manifest().get(path.name, {}) first_line = next((ln.strip() for ln in (raw[0] if raw else "").splitlines() if ln.strip() and not _BANNER.search(ln)), "") title = meta.get("title") or (meta_title.strip() if meta_title.strip().strip("()").lower() not in ("", "untitled", "anonymous") else "") \ or first_line[:90] or path.stem title = re.sub(r"^Aranya Valley University \(AVU\) \(fictional\)\s*", "", title).strip() or path.stem issued = meta.get("issued") or _to_iso(" ".join(raw[:1]))
chunks: list[Chunk] = [] for pno, text in enumerate(pages, 1): sents = split_sentences(text) for ci, ctext in enumerate(chunk_page(sents, target_words, overlap)): chunks.append(Chunk(f"{doc_id}-p{pno}-c{ci}", doc_id, path.name, title, pno, ctext, issued))
status, msg = "ok", "extracted" if not any(p.strip() for p in pages): status, msg = "warning", "no extractable text (scanned PDF? OCR is not supported)" return DocumentInfo(doc_id, path.name, title, len(pages), len(chunks), issued, status, msg, pages), chunks1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071"""Dense text embeddings.
* SentenceTransformerEmbedder - sentence-transformers/all-MiniLM-L6-v2 (384-d, Apache-2.0).* LSAEmbedder - offline fallback: TF-IDF (word 1-2 grams) + TruncatedSVD, L2-normalised. Must be fitted on the corpus; refitted when documents are added."""from __future__ import annotations
import logging
import numpy as np
import config
log = logging.getLogger(__name__)
class SentenceTransformerEmbedder: needs_fit = False
def __init__(self, model_name: str = config.EMBEDDING_MODEL): from sentence_transformers import SentenceTransformer self.model = SentenceTransformer(model_name, device="cpu") self.name = f"SentenceTransformer ({model_name})"
def fit(self, texts): # no-op, kept for a uniform interface return self
def encode(self, texts: list[str]) -> np.ndarray: v = self.model.encode(list(texts), batch_size=32, normalize_embeddings=True, show_progress_bar=False, convert_to_numpy=True) return v.astype("float32")
class LSAEmbedder: needs_fit = True
def __init__(self, dim: int = config.LSA_DIM): self.dim = dim self.name = "LSA (TF-IDF + TruncatedSVD) - offline fallback" self.vec = None self.svd = None
def fit(self, texts: list[str]): from sklearn.decomposition import TruncatedSVD from sklearn.feature_extraction.text import TfidfVectorizer self.vec = TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True, min_df=1, token_pattern=r"(?u)\b[\w.%+:-]+\b", stop_words="english") X = self.vec.fit_transform(texts) k = max(2, min(self.dim, X.shape[0] - 1, X.shape[1] - 1)) self.svd = TruncatedSVD(n_components=k, random_state=42).fit(X) return self
def encode(self, texts: list[str]) -> np.ndarray: if self.vec is None: raise RuntimeError("LSAEmbedder must be fitted before encoding") v = self.svd.transform(self.vec.transform(texts)) v /= np.linalg.norm(v, axis=1, keepdims=True) + 1e-12 return v.astype("float32")
def load_embedder(backend: str = config.EG_BACKEND): if backend in ("full", "auto"): try: return SentenceTransformerEmbedder() except Exception as e: if backend == "full": raise log.warning("Sentence Transformer unavailable (%s); using LSA fallback", e) return LSAEmbedder()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174"""SYSTEM B - EvidenceGuard RAG.
hybrid retrieval -> cross-encoder reranking -> evidence sufficiency -> contradiction detection-> context-grounded generation -> citation validation -> confidence-based abstention -> explanationEach stage can be switched off for the ablation study."""from __future__ import annotations
import reimport timefrom dataclasses import asdict
import configfrom src.baseline_rag import passage_dictsfrom src.retrieval import DenseRetriever, HybridRetrieverfrom src.reranker import rerankfrom src.text_utils import split_sentences
ABSTAIN_TEXT = ("I could not find sufficient evidence in the uploaded documents to answer this question. " "Please check with the relevant university office.")_PRESUPPOSITION = re.compile(r"^\s*(since|given that|as|because|assuming)\b", re.I)
class EvidenceGuardRAG: def __init__(self, kb, generator, reranker, verifier, use_hybrid=True, use_rerank=True, use_verification=True, top_k: int = config.TOP_K, name: str = "EvidenceGuard RAG"): self.kb, self.gen, self.reranker, self.verifier = kb, generator, reranker, verifier self.retriever = HybridRetriever(kb) if use_hybrid else DenseRetriever(kb) self.use_rerank, self.use_verification = use_rerank, use_verification self.top_k, self.name = top_k, name
# ------------------------------------------------------------------ def answer(self, question: str) -> dict: T = {} t0 = time.perf_counter() n = config.CANDIDATES if self.use_rerank else self.top_k items = self.retriever.retrieve(question, n) T["retrieval"] = time.perf_counter() - t0
t = time.perf_counter() if self.use_rerank: items = rerank(self.reranker, question, items, self.top_k) elif self.use_verification and items: # Verification needs calibrated relevance scores. Score passages for gating only; # retrieval order and the passage set stay exactly as the dense retriever returned them. for r, s in zip(items, self.reranker.score(question, [f"{r.chunk.title}. {r.chunk.text}" for r in items])): r.rerank = float(s) T["rerank"] = time.perf_counter() - t
if not self.use_verification: gen = self.gen.generate(question, items, mode="grounded") T["verification"], T["generation"] = 0.0, gen.seconds T["total"] = time.perf_counter() - t0 return self._package(question, items, gen.claims, "answered", None, [], [], None, "Verification disabled for this configuration.", T, gen.backend, [])
# ---------------- 1. sufficiency t = time.perf_counter() ordered = sorted(items, key=lambda r: -r.relevance) suff = self.verifier.sufficiency(question, ordered) if suff.status == "insufficient": T["verification"] = time.perf_counter() - t T["generation"] = 0.0 T["total"] = time.perf_counter() - t0 why = (f"Abstained: evidence is insufficient (best passage relevance {suff.max_relevance:.2f}, " f"query coverage {suff.coverage:.2f}; thresholds {self.verifier.th['min_relevance']:.2f} / " f"{self.verifier.th['min_coverage']:.2f}).") if suff.missing_terms: why += f" Question terms not found in the retrieved passages: {', '.join(suff.missing_terms[:8])}." return self._package(question, items, [], "abstained", suff, [], [], 0.0, why, T, "", [])
# ---------------- 2. conflict-search retrieval + contradiction detection + premise check items = items + self.verifier.expand_for_conflicts(question, items, self.retriever) conflicts = self.verifier.detect_conflicts(question, items) premise = [] if _PRESUPPOSITION.search(question): ev = [s for r in ordered[:3] for s in split_sentences(r.chunk.text)] premise = self.verifier.premise_issues(question, ev) T["verification"] = time.perf_counter() - t
# ---------------- 3. grounded generation gen = self.gen.generate(question, items, mode="grounded", conflicts=conflicts, premise_notes=premise) T["generation"] = gen.seconds if gen.declined: T["total"] = time.perf_counter() - t0 return self._package(question, items, [], "abstained", suff, conflicts, [], 0.0, "Abstained: the language model reported that the passages do not contain the answer.", T, gen.backend, premise)
# ---------------- 4. citation validation t = time.perf_counter() checks = self.verifier.validate_citations(gen.claims, items) T["verification"] += time.perf_counter() - t supported = [(c.sentence, c.cited or [self._best_cite(c)]) for c in checks if c.supported] ratio = len(supported) / max(1, len(checks))
# ---------------- 5. confidence & decision conf = 0.4 * min(1.0, suff.max_relevance) + 0.4 * min(1.0, suff.coverage) + 0.2 * ratio if not supported: decision, why = "abstained", "Abstained: none of the generated sentences could be verified against the cited passages." elif conf < self.verifier.th["min_confidence"]: decision, why = "abstained", f"Abstained: confidence {conf:.2f} is below the threshold {self.verifier.th['min_confidence']:.2f}." elif conflicts: decision = "conflict" why = ("Answered with a conflict warning: " + "; ".join( f"'{c.title_a}' and '{c.title_b}' disagree ({c.detail})" for c in conflicts) + ".") elif suff.status == "partial" or ratio < 1: decision = "partial" why = f"Partially answered: query coverage {suff.coverage:.2f}" if suff.missing_terms: why += f"; not covered: {', '.join(suff.missing_terms[:6])}" if ratio < 1: why += f"; {len(checks) - len(supported)} unsupported sentence(s) removed" why += "." else: decision = "answered" why = (f"Answered: relevance {suff.max_relevance:.2f}, coverage {suff.coverage:.2f}, " f"{len(supported)}/{len(checks)} sentences verified against their citations.") T["total"] = time.perf_counter() - t0 return self._package(question, items, supported if decision != "abstained" else [], decision, suff, conflicts, checks, conf, why, T, gen.backend, premise)
@staticmethod def _best_cite(check): m = re.search(r"\[(\d+)\]", check.sentence) return int(m.group(1)) if m else 1
# ------------------------------------------------------------------ def _render(self, claims, decision, conflicts, items, premise): if decision == "abstained": return ABSTAIN_TEXT parts = [] if conflicts: parts.append("⚠️ **Conflicting evidence found.** The documents disagree:") shown = set() for c in conflicts[:2]: for title, issued, sent, n in ((c.title_a, c.issued_a, c.sentence_a, c.passage_a), (c.title_b, c.issued_b, c.sentence_b, c.passage_b)): if sent in shown: continue shown.add(sent) parts.append(f"- *{title}* (issued {issued or 'unknown'}): {sent} [{n}]") newest = conflicts[0].newer if newest: parts.append(f"The more recent document is *{newest}*" + (", which explicitly revises the earlier rule." if conflicts[0].explicit_update else ".") + " Please confirm with the issuing office before relying on either version.") extra = [(s, c) for s, c in claims if s not in shown] if extra: parts.append("**Most relevant evidence:** " + " ".join(f"{s} [{', '.join(map(str, c))}]" for s, c in extra)) return "\n".join(parts) for p in premise: parts.append(f"**Note:** {p[0].upper() + p[1:]}.") parts.append(" ".join(f"{s} [{', '.join(map(str, c))}]" for s, c in claims)) return "\n\n".join(parts)
def _package(self, question, items, claims, decision, suff, conflicts, checks, conf, why, T, backend, premise): cited = sorted({c for _, cs in claims for c in cs if 1 <= c <= len(items)}) if decision == "conflict": cited = sorted(set(cited) | {n for cf in conflicts for n in (cf.passage_a, cf.passage_b)}) return { "system": self.name, "question": question, "answer": self._render(claims, decision, conflicts, items, premise), "decision": decision, "claims": claims, "citations": [{"n": c, "doc_name": items[c - 1].chunk.doc_name, "title": items[c - 1].chunk.title, "page": items[c - 1].chunk.page} for c in cited], "passages": passage_dicts(items), "sufficiency": asdict(suff) if suff else None, "conflicts": [asdict(c) for c in conflicts], "citation_checks": [asdict(c) for c in checks], "premise_notes": premise, "confidence": None if conf is None else round(conf, 3), "explanation": why, "timings": T, "generator": backend, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203"""Evaluation metrics for EvidenceGuard AI (all computed from the generated question set).
Retrieval Precision@K, Recall@K, MRR (gold unit = document + page)Answer quality Answer correctness (key-fact match / correct abstention), Faithfulness (claims supported by the retrieved context), Evidence-grounded faithfulness (claims that come from the gold evidence pages), Answer relevance (TF-IDF cosine question vs answer - lexical proxy), Context precision (rank-weighted AP@K), Context recall (key facts present in context)Reliability Unsupported answer rate, Abstention accuracy/P/R/F1, Contradiction detection P/R/F1, Citation support accuracy, Behaviour accuracyEfficiency mean total / retrieval / generation / verification time (seconds)"""from __future__ import annotations
import reimport statistics as st
from src.text_utils import fact_values, keyword_present, normalize, split_sentences
_ABSTAIN_PAT = re.compile(r"(could not find sufficient evidence|insufficient_evidence|do(es)? not (contain|mention|" r"provide|specify)|not (mentioned|specified|available) in|no information)", re.I)
def is_abstention(result: dict) -> bool: return result["decision"] == "abstained" or bool(_ABSTAIN_PAT.search(result["answer"] or ""))
def _gold_units(q): return {(e["doc_id"], e["page"]) for e in q["evidence"]}
def _support(sentence: str, text: str) -> bool: """Loose support check used only for evaluation: values present + >=70% token overlap.""" s_vals, t_vals = fact_values(sentence), fact_values(text) if s_vals - t_vals: return False st_ = set(re.findall(r"[a-z0-9]+", normalize(sentence))) tt = set(re.findall(r"[a-z0-9]+", normalize(text))) return len(st_ & tt) / max(1, len(st_)) >= 0.7
def score_question(q: dict, r: dict, page_text: dict, relevance_fn=None) -> dict: gold = _gold_units(q) ctx = r["passages"] units = [(p["doc_id"], p["page"]) for p in ctx] k = max(1, len(units)) rel_flags = [u in gold for u in units] has_gold = bool(gold) abst = is_abstention(r) exp_abst = q["expected_behaviour"] == "abstain" answer = r["answer"] or "" kws = q["answer_keywords"] kw_hits = [keyword_present(answer, kw) for kw in kws] ctx_text = " ".join(p["text"] for p in ctx)
# ---------------- correctness if exp_abst: correct = abst else: correct = (not abst) and all(kw_hits) flagged = r["decision"] == "conflict" or bool(r.get("conflicts")) if q["expected_behaviour"] == "flag_conflict": behaviour_ok = (not abst) and flagged and all(kw_hits) elif exp_abst: behaviour_ok = abst else: behaviour_ok = (not abst) and all(kw_hits)
# ---------------- faithfulness of answer claims claims = [s for s, _ in r.get("claims", [])] if r.get("claims") else split_sentences(answer) claims = [c for c in claims if len(c.split()) >= 3] if not abst and claims: faith = sum(_support(c, ctx_text) for c in claims) / len(claims) gold_text = " ".join(page_text[u] for u in gold) gfaith = (sum(_support(c, gold_text) for c in claims) / len(claims)) if gold else 0.0 else: faith = gfaith = None
# ---------------- citations cited = r.get("citations", []) if not abst and cited: cite_acc = sum((c_doc_id(c, ctx), c["page"]) in gold for c in cited) / len(cited) else: cite_acc = None
# ---------------- context precision (AP@K) and recall (key facts in context) if has_gold: hits, ap = 0, 0.0 for i, f in enumerate(rel_flags, 1): if f: hits += 1 ap += hits / i ctx_precision = ap / max(1, hits) if hits else 0.0 ctx_recall = (sum(keyword_present(ctx_text, kw) for kw in kws) / len(kws)) if kws else None p_at_k = sum(rel_flags) / k r_at_k = len(gold & set(units)) / len(gold) rr = next((1 / i for i, f in enumerate(rel_flags, 1) if f), 0.0) else: ctx_precision = ctx_recall = p_at_k = r_at_k = rr = None
return { "id": q["id"], "category": q["category"], "question": q["question"], "expected_behaviour": q["expected_behaviour"], "expected_status": q["expected_evidence_status"], "decision": r["decision"], "abstained": abst, "conflict_flagged": flagged, "answer": answer, "expected_answer": q["expected_answer"], "keywords_hit": sum(kw_hits), "keywords_total": len(kws), "correct": correct, "behaviour_ok": behaviour_ok, "unsupported": (not abst) and (exp_abst or (kws and not any(kw_hits))), "faithfulness": faith, "grounded_faithfulness": gfaith, "answer_relevance": (relevance_fn(q["question"], answer) if (relevance_fn and not abst) else None), "citation_support": cite_acc, "precision_at_k": p_at_k, "recall_at_k": r_at_k, "mrr": rr, "context_precision": ctx_precision, "context_recall": ctx_recall, "confidence": r.get("confidence"), "t_total": r["timings"]["total"], "t_retrieval": r["timings"]["retrieval"] + r["timings"].get("rerank", 0), "t_generation": r["timings"]["generation"], "t_verification": r["timings"].get("verification", 0.0), "explanation": r.get("explanation", ""), "retrieved": "; ".join(f"{d} p.{p}" for d, p in units), }
def c_doc_id(c, ctx): for p in ctx: if p["n"] == c["n"]: return p["doc_id"] return ""
def _mean(xs): xs = [x for x in xs if x is not None] return round(st.mean(xs), 4) if xs else None
def _prf(pred, gold): tp = sum(p and g for p, g in zip(pred, gold)) fp = sum(p and not g for p, g in zip(pred, gold)) fn = sum((not p) and g for p, g in zip(pred, gold)) prec = tp / (tp + fp) if tp + fp else 0.0 rec = tp / (tp + fn) if tp + fn else 0.0 f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0 acc = sum(p == g for p, g in zip(pred, gold)) / max(1, len(gold)) return round(prec, 4), round(rec, 4), round(f1, 4), round(acc, 4)
def aggregate(rows: list[dict]) -> dict: ap, ar, af, aa = _prf([r["abstained"] for r in rows], [r["expected_behaviour"] == "abstain" for r in rows]) cp, cr, cf, ca = _prf([r["conflict_flagged"] for r in rows], [r["expected_status"] == "conflicting" for r in rows]) out = { "n_questions": len(rows), # retrieval "precision_at_k": _mean(r["precision_at_k"] for r in rows), "recall_at_k": _mean(r["recall_at_k"] for r in rows), "mrr": _mean(r["mrr"] for r in rows), # answer quality "answer_correctness": _mean(float(r["correct"]) for r in rows), "faithfulness": _mean(r["faithfulness"] for r in rows), "grounded_faithfulness": _mean(r["grounded_faithfulness"] for r in rows), "answer_relevance": _mean(r["answer_relevance"] for r in rows), "context_precision": _mean(r["context_precision"] for r in rows), "context_recall": _mean(r["context_recall"] for r in rows), # reliability "unsupported_answer_rate": _mean(float(r["unsupported"]) for r in rows), "abstention_accuracy": aa, "abstention_precision": ap, "abstention_recall": ar, "abstention_f1": af, "abstention_rate": _mean(float(r["abstained"]) for r in rows), "contradiction_precision": cp, "contradiction_recall": cr, "contradiction_f1": cf, "contradiction_accuracy": ca, "citation_support_accuracy": _mean(r["citation_support"] for r in rows), "behaviour_accuracy": _mean(float(r["behaviour_ok"]) for r in rows), # efficiency "avg_response_time_s": _mean(r["t_total"] for r in rows), "avg_retrieval_time_s": _mean(r["t_retrieval"] for r in rows), "avg_generation_time_s": _mean(r["t_generation"] for r in rows), "avg_verification_time_s": _mean(r["t_verification"] for r in rows), } return out
def by_category(rows: list[dict]) -> dict: cats = sorted({r["category"] for r in rows}) return {c: {"n": sum(r["category"] == c for r in rows), "answer_correctness": _mean(float(r["correct"]) for r in rows if r["category"] == c), "behaviour_accuracy": _mean(float(r["behaviour_ok"]) for r in rows if r["category"] == c), "unsupported_rate": _mean(float(r["unsupported"]) for r in rows if r["category"] == c), "abstention_rate": _mean(float(r["abstained"]) for r in rows if r["category"] == c)} for c in cats}
def classify_error(r: dict) -> str: """Coarse error taxonomy used in the error analysis.""" if r["behaviour_ok"]: return "correct" eb = r["expected_behaviour"] if eb == "abstain": return "answered unanswerable question (hallucination risk)" if r["abstained"]: return "over-abstention (answer was available)" if eb == "flag_conflict" and not r["conflict_flagged"]: return "missed conflict" if r["recall_at_k"] is not None and r["recall_at_k"] == 0: return "retrieval failure (no gold page retrieved)" if r["keywords_hit"] == 0: return "wrong/irrelevant answer content" return "incomplete answer (some key facts missing)"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410"""Evidence verification layer of EvidenceGuard AI.
1. Evidence sufficiency - is the question actually covered by the retrieved passages?2. Contradiction detection - do relevant passages from different documents disagree?3. Citation validation - is every answer sentence supported by the passage it cites?
Two interchangeable judges are provided: * NLIJudge : cross-encoder/nli-deberta-v3-xsmall (Apache-2.0), probabilities for contradiction / entailment / neutral. * no NLI : rule-based checks only (numeric value mismatch, polarity/negation flip, lexical & numeric support). Always active - NLI models are known to be weak at comparing numbers, which dominate policy documents, so the numeric rule is kept even when NLI is available (union of both signals)."""from __future__ import annotations
import loggingimport refrom dataclasses import asdict, dataclass, field
import numpy as np
import configfrom src.text_utils import (DOMAIN_STOPWORDS, content_tokens, extract_facts, fact_occurrences, fact_values, split_sentences, tokenize)
log = logging.getLogger(__name__)
_NEG = re.compile(r"\b(not|cannot|no|never|without)\b")_UPDATE_CUE = re.compile(r"\b(supersedes?|revised to|extended to|with effect from|amendment|is revised)\b", re.I)_BOILERPLATE = re.compile(r"Document No\.|Issued by:|Effective from", re.I)
def stem(t: str) -> str: """Tiny suffix stripper (plural / -ed / -ing); enough to match 'electives' with 'elective'.""" if len(t) <= 3 or not t.isalpha() and "-" not in t: return t if t.endswith("ies") and len(t) > 4: return t[:-3] + "y" if t.endswith(("sses", "xes", "ches", "shes")): return t[:-2] if t.endswith("s") and not t.endswith(("ss", "us", "is")): t = t[:-1] for suf in ("ing", "ed"): if len(t) > 5 and t.endswith(suf): return t[: -len(suf)] return t
def stems(text: str, drop_domain: bool = False) -> set[str]: return {stem(t) for t in content_tokens(text, drop_domain=drop_domain)}
def topic_tokens(text: str) -> set[str]: """Content stems without numbers - what a sentence is *about*.""" return {stem(t) for t in content_tokens(text, drop_domain=True) if not re.match(r"^\d", t) and t not in {"inr", "per", "up", "least"}}
def is_negated(text: str) -> bool: return bool(_NEG.search(text.lower()))
def negated_predicates(text: str) -> set[str]: """Stems of the words a negation applies to: 'will not be accepted' -> {'accept'}.""" out = set() for m in re.finditer(r"\b(?:not|cannot|never)\s+(?:be\s+|been\s+)?([a-z]+)", text.lower()): w = stem(m.group(1)) out.add(w[:-2] if w.endswith("ed") else w) return out
# ====================================================================== NLIclass NLIJudge: def __init__(self, model_name: str = config.NLI_MODEL): from sentence_transformers import CrossEncoder self.model = CrossEncoder(model_name, device="cpu") cfg = getattr(self.model, "config", None) or self.model.model.config self.labels = {int(k): v.lower() for k, v in cfg.id2label.items()} self.name = f"NLI cross-encoder ({model_name})"
def probs(self, pairs: list[tuple[str, str]]) -> list[dict]: if not pairs: return [] logits = np.asarray(self.model.predict(pairs, show_progress_bar=False), dtype="float64") if logits.ndim == 1: logits = logits[None, :] e = np.exp(logits - logits.max(axis=1, keepdims=True)) p = e / e.sum(axis=1, keepdims=True) return [{self.labels[j]: float(row[j]) for j in range(row.shape[0])} for row in p]
def load_nli(backend: str = config.EG_BACKEND): if backend in ("full", "auto"): try: return NLIJudge() except Exception as e: if backend == "full": raise log.warning("NLI model unavailable (%s); using rule-based verification only", e) return None
# ====================================================================== results@dataclassclass Sufficiency: status: str # sufficient | partial | insufficient max_relevance: float coverage: float # combined coverage score coverage_single: float coverage_union: float missing_terms: list = field(default_factory=list)
@dataclassclass Conflict: doc_a: str title_a: str page_a: int issued_a: str sentence_a: str doc_b: str title_b: str page_b: int issued_b: str sentence_b: str kind: str # numeric | polarity | nli detail: str newer: str # title of the more recent document ("" if unknown) explicit_update: bool passage_a: int = 0 # 1-based index in the context list passage_b: int = 0
@dataclassclass CitationCheck: sentence: str cited: list supported: bool score: float reason: str
# ====================================================================== verifierclass EvidenceVerifier: def __init__(self, kb, nli: NLIJudge | None = None, thresholds: dict | None = None): self.kb = kb self.nli = nli self.th = thresholds or config.load_thresholds()
@property def name(self): return (self.nli.name + " + numeric/polarity rules") if self.nli else \ "Rule-based verifier (numeric mismatch, polarity flip, lexical support) - offline fallback"
# ------------------------------------------------------------------ 1. sufficiency def query_terms(self, question: str) -> list[str]: q = list(dict.fromkeys(stem(t) for t in content_tokens(question, drop_domain=True))) return q or list(dict.fromkeys(stem(t) for t in content_tokens(question)))
def _weight(self, term: str) -> float: # IDF is stored for raw tokens; try stem and common surface forms. for cand in (term, term + "s", term + "es", term + "ed", term + "ing"): if self.kb.in_vocab(cand): return self.kb.term_idf(cand) return self.kb.max_idf + 1.0
def sufficiency(self, question: str, items) -> Sufficiency: terms = self.query_terms(question) if not items or not terms: return Sufficiency("insufficient", 0.0, 0.0, 0.0, 0.0, terms) w = {t: self._weight(t) for t in terms} total = sum(w.values()) top = items[:3] pst = [stems(f"{r.chunk.title}. {r.chunk.text}") for r in top] single = max(sum(w[t] for t in terms if t in s) / total for s in pst) union_set = set().union(*pst) union = sum(w[t] for t in terms if t in union_set) / total cov = 0.5 * single + 0.5 * union surface = {stem(t): t for t in content_tokens(question)} # stem -> word as typed missing = [t for t in terms if t not in union_set] # Content words that never occur anywhere in the collection (e.g. "revaluation", # "convocation") mean the topic itself is absent: never offer a partial answer then. oov = [t for t in missing if not re.match(r"^\d", t) and not any( self.kb.in_vocab(c) for c in (t, t + "s", t + "es", t + "ed", t + "ing"))] rel = max(r.relevance for r in items) if rel >= self.th["min_relevance"] and cov >= self.th["min_coverage"]: status = "sufficient" elif rel >= self.th["min_relevance"] * 0.8 and cov >= self.th["partial_coverage"] and not oov: status = "partial" else: status = "insufficient" return Sufficiency(status, float(rel), float(cov), float(single), float(union), [surface.get(t, t) for t in missing])
def sentence_coverage(self, question: str, sentence: str) -> float: terms = self.query_terms(question) if not terms: return 0.0 w = {t: self._weight(t) for t in terms} st = stems(sentence) return sum(w[t] for t in terms if t in st) / sum(w.values())
# ------------------------------------------------------------------ 2. contradiction detection def expand_for_conflicts(self, question: str, items, retriever, k: int = 4): """Conflict-search retrieval.
Competing versions of a rule are often *not* in the top-k for the question (an amendment circular is short and phrased differently). Each of the best evidence sentences is used as a new query; passages from OTHER documents that come back are added as conflict candidates. """ from src.retrieval import Retrieved if retriever is None: return [] have = {r.chunk.chunk_id for r in items} docs = {r.chunk.doc_id for r in items} anchors = [a for a in sorted(self._relevant_sentences(question, items), key=lambda x: -x[3]) if a[3] >= self.th["conflict_sentence_coverage"] and (extract_facts(a[2]) or is_negated(a[2]))][:3] extra = [] for _, r, s, _ in anchors: for cand in retriever.retrieve(s, k): c = cand.chunk if c.chunk_id in have or c.doc_id == r.chunk.doc_id: continue sim = max((self._topic_sim(s, x) for x in split_sentences(c.text)), default=0.0) if sim >= self.th["conflict_topic_sim"]: have.add(c.chunk_id) extra.append(Retrieved(c, cand.score, dense=cand.dense, sparse=cand.sparse, rerank=r.relevance * 0.99, source="conflict-search")) del docs return extra
def _relevant_sentences(self, question: str, items): """Sentences that are themselves about the question (not merely in a relevant chunk).""" out = [] for idx, r in enumerate(items, 1): expansion = getattr(r, "source", "") == "conflict-search" if r.relevance < self.th["conflict_min_relevance"] and not expansion: continue for s in split_sentences(r.chunk.text): if _BOILERPLATE.search(s) or len(s.split()) < 5: continue cov = self.sentence_coverage(question, s) if cov >= self.th["conflict_sentence_coverage"] * 0.5: out.append((idx, r, s, cov)) return out
@staticmethod def _topic_sim(a: str, b: str) -> float: """Overlap coefficient of the (number-free) content stems of two sentences.""" ta, tb = topic_tokens(a), topic_tokens(b) if not ta or not tb: return 0.0 return len(ta & tb) / min(len(ta), len(tb))
def _numeric_clash(self, question: str, a: str, b: str, min_shared: int = 2): """Same kind of value, different number, described by overlapping words around it.
Two extra guards against false alarms: * the value must be of the type the question asks about ("how many marks" -> marks); * the question words that sit next to the value must agree in both sentences (8 books for *research scholars* is not a conflict with 6 books for *PG students*). """ from src.llm_generator import expected_answer_type want = expected_answer_type(question) qt = set(self.query_terms(question)) best = None sa_st, sb_st = stems(a), stems(b) for ua, va, ca in fact_occurrences(a, before=75, after=40): if want and ua not in want: continue wa = topic_tokens(ca) for ub, vb, cb in fact_occurrences(b, before=75, after=40): if ua != ub or va == vb: continue if ua not in ("date", "time"): x, y = float(va), float(vb) if min(x, y) > 0 and max(x, y) / min(x, y) > 5: # different quantities, not versions continue wb = topic_tokens(cb) shared = wa & wb # question words describing either value must also occur in the other sentence near_q = (wa | wb) & qt if near_q: missing = {t for t in near_q if not (t in sa_st and t in sb_st)} if sum(self._weight(t) for t in missing) / sum(self._weight(t) for t in near_q) > \ self.th["conflict_subject_mismatch"]: continue if (len(shared) >= min_shared or shared & qt) and (best is None or len(shared) > best[0]): best = (len(shared), f"{ua}: {va} vs {vb} (context: {', '.join(sorted(shared)[:4])})") return best[1] if best else None
def detect_conflicts(self, question: str, items) -> list[Conflict]: sents = self._relevant_sentences(question, items) best_cov = max((x[3] for x in sents), default=0.0) pairs = [] for i in range(len(sents)): for j in range(i + 1, len(sents)): (ia, ra, sa, ca_), (ib, rb, sb, cb_) = sents[i], sents[j] if ra.chunk.doc_id == rb.chunk.doc_id: continue # one side must be (close to) the best-matching evidence sentence if max(ca_, cb_) < max(self.th["conflict_sentence_coverage"], 0.8 * best_cov): continue pairs.append((self._topic_sim(sa, sb), ia, ra, sa, ib, rb, sb, sents[i][3] + sents[j][3])) # Most query-relevant pairs first, so the reported conflict is the one the user asked about. pairs.sort(key=lambda p: -p[7]) pairs = [p[:7] for p in pairs] nli_probs = [] if self.nli and pairs: nli_probs = self.nli.probs([(p[3], p[6]) for p in pairs]) found, seen = [], set() for k, (sim, ia, ra, sa, ib, rb, sb) in enumerate(pairs): kind, detail = None, "" clash = self._numeric_clash(question, sa, sb, int(self.th["conflict_min_shared"])) if clash: kind, detail = "numeric", clash elif is_negated(sa) != is_negated(sb) and sim >= self.th["conflict_topic_sim"] and \ any(p in {x[:len(p)] for x in stems(sb if is_negated(sa) else sa)} for p in negated_predicates(sa if is_negated(sa) else sb)): kind, detail = "polarity", "one passage permits what the other rules out" elif nli_probs and nli_probs[k].get("contradiction", 0) >= self.th["nli_contradiction"] \ and sim >= self.th["conflict_topic_sim"]: kind, detail = "nli", f"NLI contradiction p={nli_probs[k]['contradiction']:.2f}" if not kind: continue key = tuple(sorted([ra.chunk.doc_id, rb.chunk.doc_id])) if key in seen: continue seen.add(key) ca, cb = ra.chunk, rb.chunk newer = "" if ca.issued and cb.issued and ca.issued != cb.issued: newer = ca.title if ca.issued > cb.issued else cb.title explicit = bool(_UPDATE_CUE.search(sa) or _UPDATE_CUE.search(sb) or _UPDATE_CUE.search(ca.text) and ca.issued >= cb.issued or _UPDATE_CUE.search(cb.text) and cb.issued >= ca.issued) found.append(Conflict(ca.doc_id, ca.title, ca.page, ca.issued, sa, cb.doc_id, cb.title, cb.page, cb.issued, sb, kind, detail, newer, explicit, ia, ib)) return found[:3]
# ------------------------------------------------------------------ 3. citation validation def _lexical_support(self, sentence: str, passage: str) -> tuple[float, str]: s_vals, p_vals = fact_values(sentence), fact_values(passage) missing_vals = s_vals - p_vals st = stems(re.sub(r"\[\d+\]", "", sentence)) pt = stems(passage) overlap = len(st & pt) / max(1, len(st)) if missing_vals: return min(overlap, 0.2), f"values {sorted(missing_vals)} not found in cited passage" return overlap, f"token overlap {overlap:.2f}"
def validate_citations(self, claims, items) -> list[CitationCheck]: checks = [] texts = [f"{r.chunk.title}. {r.chunk.text}" for r in items] nli_inputs = [] for sent, cited in claims: cited_ok = [c for c in cited if 1 <= c <= len(items)] pool = cited_ok or list(range(1, len(items) + 1)) best, reason, best_c = -1.0, "no passage", [] for c in pool: sc, why = self._lexical_support(sent, texts[c - 1]) if sc > best: best, reason, best_c = sc, why, [c] checks.append(CitationCheck(sent, cited_ok, best >= self.th["citation_overlap"], float(best), reason if cited_ok else "uncited sentence; " + reason)) nli_inputs.append((texts[best_c[0] - 1] if best_c else "", sent)) if self.nli and checks: probs = self.nli.probs([(p, re.sub(r"\[\d+\]", "", h)) for p, h in nli_inputs]) for chk, pr in zip(checks, probs): ent = pr.get("entailment", 0.0) if not chk.supported and ent >= self.th["nli_entailment"] and "not found" not in chk.reason: chk.supported, chk.reason = True, chk.reason + f"; NLI entailment {ent:.2f}" else: chk.reason += f"; NLI entailment {ent:.2f}" return checks
# ------------------------------------------------------------------ premise check @staticmethod def premise_issues(question: str, evidence_sentences: list[str]) -> list[str]: """Values asserted in the question that the evidence states differently.
For every value in the question (e.g. "50 marks" in "Given that internal assessment carries 50 marks ...") find the evidence value of the same unit whose surrounding words best match the question's words around it; report it if the numbers differ. """ issues = [] for uq, vq, cq in fact_occurrences(question, before=45, after=30): wq = topic_tokens(cq) best = None for s in evidence_sentences: for ue, ve, ce in fact_occurrences(s, before=45, after=30): if ue != uq: continue shared = len(wq & topic_tokens(ce)) if shared >= 1 and (best is None or shared > best[0]): best = (shared, ve) if best and best[1] != vq: unit = "" if uq == "%" else f" {uq}" issues.append(f"the question assumes {vq}{unit}, but the documents state {best[1]}{unit}") return issues
def to_dict(obj): return asdict(obj) if hasattr(obj, "__dataclass_fields__") else obj
__all__ = ["EvidenceVerifier", "load_nli", "Sufficiency", "Conflict", "CitationCheck", "to_dict", "DOMAIN_STOPWORDS", "tokenize"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244"""Answer generation.
Backends HFInferenceGenerator - Hugging Face Inference Providers (huggingface_hub.InferenceClient), token read from the HF_TOKEN environment variable / Space secret. LocalLLMGenerator - small instruction-tuned model (default Qwen/Qwen2.5-0.5B-Instruct, Apache-2.0) run on CPU with transformers, greedy decoding. ExtractiveGenerator - no LLM: composes the answer from the retrieved sentences that best cover the question (offline fallback; cannot hallucinate new text, but can still pick an irrelevant sentence - which is exactly the failure EvidenceGuard's verification layer is designed to catch).
Every backend returns GenOutput with a list of (sentence, [cited passage numbers]) claims,so citation validation works the same way for all of them."""from __future__ import annotations
import loggingimport reimport timefrom dataclasses import dataclass, field
import configfrom src.text_utils import content_tokens, extract_facts, split_sentences
log = logging.getLogger(__name__)
def expected_answer_type(question: str) -> set[str]: """Light answer-type detection (classic QA technique): which kind of value is asked for.""" q = question.lower() m = re.search(r"\bhow many (working days|contact hours|days|books|marks|credits|minutes|semesters|years|" r"members|weeks|months|hours)\b", q) if m: unit = m.group(1) return {"days", "working days"} if unit in ("days", "working days") else {unit} if re.search(r"\bhow many [a-z-]+", q) and not re.search(r"\bhow many (times|of)\b", q): return {"count"} # e.g. "how many open electives": a count, not a unit value if re.search(r"\b(timings?|what time|at what time)\b", q): return {"time"} if re.search(r"\b(when|what date|which date|on what date|last date|deadline|by when)\b", q): return {"date"} if re.search(r"\b(fee|fine|cost|amount|charged)\b", q): return {"inr"} if re.search(r"\b(percentage|percent)\b", q): return {"%"} if re.search(r"\bhow long\b", q): return {"days", "working days", "minutes", "semesters", "years", "weeks", "months"} if re.search(r"\bhow (many|much)\b", q): return {"days", "working days", "books", "marks", "credits", "minutes", "semesters", "years", "members", "%", "inr", "mb", "contact hours", "weeks", "months"} return set()
INSUFFICIENT = "INSUFFICIENT_EVIDENCE"
BASELINE_SYSTEM = ("You are a helpful university assistant. Answer the user's question using the " "context passages. Cite the passages you use like [1].")
GROUNDED_SYSTEM = ( "You are EvidenceGuard, a careful university policy assistant.\n" "Rules:\n" "1. Use ONLY the numbered context passages. Never use outside knowledge.\n" "2. End every sentence with the passage number(s) that support it, e.g. [2].\n" f"3. If the passages do not contain the answer, reply with exactly: {INSUFFICIENT}\n" "4. If the passages disagree, state each version with its citation and say which document is more recent.\n" "5. If the question contains a false assumption, correct it.\n" "6. Answer in at most 4 short sentences.")
@dataclassclass GenOutput: text: str claims: list = field(default_factory=list) # [(sentence, [passage numbers])] backend: str = "" seconds: float = 0.0 declined: bool = False # model itself said evidence is insufficient
def format_context(items) -> str: lines = [] for i, r in enumerate(items, 1): c = r.chunk lines.append(f"[{i}] ({c.title}, page {c.page}, issued {c.issued or 'unknown'}) {c.text}") return "\n".join(lines)
def build_messages(question: str, items, mode: str, conflicts=None, premise_notes=None): system = GROUNDED_SYSTEM if mode == "grounded" else BASELINE_SYSTEM user = f"Context passages:\n{format_context(items)}\n\nQuestion: {question}" if mode == "grounded" and conflicts: user += "\n\nVerifier note: these passages conflict: " + "; ".join( f"[{c.passage_a}] vs [{c.passage_b}] ({c.detail}); newer document: {c.newer or 'unknown'}" for c in conflicts) if mode == "grounded" and premise_notes: user += "\n\nVerifier note: " + "; ".join(premise_notes) return [{"role": "system", "content": system}, {"role": "user", "content": user}]
def parse_claims(text: str) -> list[tuple[str, list[int]]]: claims = [] for s in split_sentences(text.replace("\n", " ")): cites = [int(x) for x in re.findall(r"\[(\d+)\]", s)] clean = re.sub(r"\s*\[\d+\](?:\s*\[\d+\])*", "", s).strip() if clean: claims.append((clean, cites)) return claims
# ====================================================================== LLM backendsclass HFInferenceGenerator: def __init__(self, model: str = config.HF_API_MODEL, token: str | None = config.HF_TOKEN): if not token: raise RuntimeError("HF_TOKEN is not set") from huggingface_hub import InferenceClient self.client = InferenceClient(model=model, token=token, timeout=60) self.name = f"HF Inference API ({model})"
def complete(self, messages) -> str: r = self.client.chat_completion(messages=messages, max_tokens=config.MAX_NEW_TOKENS, temperature=max(0.01, config.TEMPERATURE)) return r.choices[0].message.content or ""
class LocalLLMGenerator: def __init__(self, model: str = config.LOCAL_LLM_MODEL): import torch from transformers import AutoModelForCausalLM, AutoTokenizer self.torch = torch self.tok = AutoTokenizer.from_pretrained(model) self.model = AutoModelForCausalLM.from_pretrained(model, dtype=torch.float32) self.model.eval() self.name = f"Local transformers ({model}, CPU)"
def complete(self, messages) -> str: prompt = self.tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) ids = self.tok(prompt, return_tensors="pt") with self.torch.no_grad(): out = self.model.generate(**ids, max_new_tokens=config.MAX_NEW_TOKENS, do_sample=False, pad_token_id=self.tok.eos_token_id) return self.tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True).strip()
# ====================================================================== extractive backendclass ExtractiveGenerator: name = "Extractive composer (no LLM) - offline fallback"
def __init__(self, kb): self.kb = kb
def select(self, question: str, items, max_sents: int = 3): from src.evidence_verifier import stem, stems q = list(dict.fromkeys(stem(t) for t in content_tokens(question, drop_domain=True))) q = q or list(dict.fromkeys(stem(t) for t in content_tokens(question))) if not items: return [] 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) for t in q} total = sum(w.values()) or 1.0 want = expected_answer_type(question) cands = [] for i, r in enumerate(items, 1): for s in split_sentences(r.chunk.text): if re.search(r"Document No\.|Issued by:|^Aranya Valley University", s) or len(s.split()) < 6: continue units = {f.split(":", 1)[0] for f in extract_facts(s)} bonus = 0.15 if want and (want & units) else 0.0 cands.append((i, r, s, stems(s), bonus)) if not cands: return [] chosen, covered = [], set() for _ in range(max_sents): best, best_gain = None, 0.0 for i, r, s, st, bonus in cands: if any(s == c[0] for c in chosen): continue gain = sum(w[t] for t in q if t in st and t not in covered) / total score = gain + 0.15 * r.relevance - 0.02 * (i - 1) + (bonus if not chosen else 0.0) if best is None or score > best[0]: best, best_gain = (score, i, s, st), gain if best is None or (chosen and best_gain < 0.12): break chosen.append((best[2], [best[1]])) covered |= {t for t in q if t in best[3]} return chosen
# ====================================================================== facadeclass AnswerGenerator: """Chooses an LLM backend once and exposes generate(question, items, mode, ...)."""
def __init__(self, kb, backend: str = config.LLM_BACKEND): self.extractive = ExtractiveGenerator(kb) self.llm = None self.requested = backend self.error = "" if backend in ("auto", "hf_api") and config.HF_TOKEN: try: self.llm = HFInferenceGenerator() except Exception as e: self.error = f"HF API unavailable: {e}" if self.llm is None and backend in ("auto", "local"): try: self.llm = LocalLLMGenerator() except Exception as e: self.error = (self.error + "; " if self.error else "") + f"local LLM unavailable: {e}" if self.llm is None and backend not in ("extractive", "auto"): log.warning("Requested LLM backend %s unavailable (%s); using extractive", backend, self.error)
@property def name(self): return self.llm.name if self.llm else self.extractive.name
def generate(self, question: str, items, mode: str = "baseline", conflicts=None, premise_notes=None) -> GenOutput: t0 = time.perf_counter() if self.llm is not None: try: text = self.llm.complete(build_messages(question, items, mode, conflicts, premise_notes)) declined = INSUFFICIENT in text claims = [] if declined else parse_claims(text) return GenOutput(text, claims, self.llm.name, time.perf_counter() - t0, declined) except Exception as e: # network / quota errors -> graceful fallback log.warning("LLM call failed (%s); falling back to extractive", e) return self._extractive(question, items, mode, conflicts, premise_notes, t0)
def _extractive(self, question, items, mode, conflicts, premise_notes, t0) -> GenOutput: if mode == "grounded" and conflicts: claims = [] for c in conflicts[:2]: claims.append((c.sentence_a, [c.passage_a])) claims.append((c.sentence_b, [c.passage_b])) # add the best directly relevant sentence(s) too, so the answer stays on the question claims += self.extractive.select(question, items, max_sents=2) seen, uniq = set(), [] for s, ci in claims: if s not in seen: uniq.append((s, ci)) seen.add(s) claims = uniq else: claims = self.extractive.select(question, items) text = " ".join(f"{s} [{','.join(map(str, c))}]" for s, c in claims) return GenOutput(text, claims, self.extractive.name, time.perf_counter() - t0).gitattributes+2
README.md+136-5
app.pyAdded+524
assets/architecture.pngAdded

Large File Pointer Details
- SHA256: 60157a386c610c1abee3bf190971b37265ee2d6e345a7d70d3239fa206f49cba
- Pointer size: 131 Bytes
- Size of remote file: 220 kB
assets/workflow.pngAdded

Large File Pointer Details
- SHA256: b853e69092c8c68bd00a1f5236424d29c78a88d7dfd7ecf90da56f207a974398
- Pointer size: 131 Bytes
- Size of remote file: 157 kB
config.pyAdded+104
requirements.txtAdded+19
results/calibrated_thresholds.jsonAdded+51
results/category_breakdown.csvAdded+21
results/charts/answer_quality_comparison.pngAdded

results/charts/category_breakdown.pngAdded

results/charts/error_analysis.pngAdded

results/charts/reliability_comparison.pngAdded

results/charts/response_time.pngAdded

results/charts/retrieval_comparison.pngAdded

results/error_analysis.csvAdded+7
results/failure_cases.jsonAdded+584
results/metrics.csvAdded+13
results/metrics.jsonAdded+537
results/per_question_results.csvAdded
results/significance.jsonAdded+158
scripts/build_report.pyAdded+492
scripts/corpus_content.pyAdded+618
scripts/generate_dataset.pyAdded+156
scripts/make_diagrams.pyAdded+130
scripts/questions_spec.pyAdded+334
scripts/render_report_docx.jsAdded+139
scripts/run_evaluation.pyAdded+316
scripts/significance.pyAdded+57
src/__init__.pyAdded
src/__pycache__/__init__.cpython-312.pycAdded
src/__pycache__/baseline_rag.cpython-312.pycAdded
src/__pycache__/document_processor.cpython-312.pycAdded
src/__pycache__/embeddings.cpython-312.pycAdded
src/__pycache__/enhanced_rag.cpython-312.pycAdded
src/__pycache__/evidence_verifier.cpython-312.pycAdded
src/__pycache__/llm_generator.cpython-312.pycAdded
src/__pycache__/reranker.cpython-312.pycAdded
src/__pycache__/research.cpython-312.pycAdded
src/__pycache__/retrieval.cpython-312.pycAdded
src/__pycache__/system.cpython-312.pycAdded
src/__pycache__/text_utils.cpython-312.pycAdded
src/__pycache__/vector_store.cpython-312.pycAdded
src/baseline_rag.pyAdded+60
src/document_processor.pyAdded+154
src/embeddings.pyAdded+71
src/enhanced_rag.pyAdded+174
src/evaluation.pyAdded+203
src/evidence_verifier.pyAdded+410
src/llm_generator.pyAdded+244