File size: 7,963 Bytes
4f6c209
 
a805048
4f6c209
a805048
4f6c209
 
a805048
4f6c209
 
a805048
 
4f6c209
 
a805048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
---
title: EvidenceGuard AI
emoji: πŸ›‘οΈ
colorFrom: blue
colorTo: yellow
sdk: gradio
sdk_version: 6.32.0
python_version: "3.12"
app_file: app.py
pinned: false
license: apache-2.0
short_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 two
documents give different versions of the same rule. EvidenceGuard AI checks that **sufficient and consistent
evidence** exists before answering. Otherwise it gives a partial answer, shows both conflicting versions (and
names 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).

![architecture](assets/architecture.png)

## 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 cannot
be loaded. `EG_BACKEND=lite` forces the offline components (fast, no downloads).

## Run locally

```bash
python -m venv .venv && source .venv/bin/activate      # Windows: .venv\Scripts\activate
pip install -r requirements.txt
python app.py                                          # http://127.0.0.1:7860
```

Fully offline / fastest start: `EG_BACKEND=lite LLM_BACKEND=extractive python app.py`

Regenerate everything:

```bash
python scripts/generate_dataset.py                                  # PDFs + 100 questions
python scripts/run_evaluation.py --backend lite --llm extractive    # results/ + charts (β‰ˆ25 s on CPU)
python scripts/significance.py                                      # McNemar + bootstrap CIs
python scripts/make_diagrams.py                                     # assets/*.png
pip install -r requirements-dev.txt && python -m pytest -q          # tests
python 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). Thresholds
are 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 this
small 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 same
question set (only thresholds were calibrated on the DEV split), so the test numbers are optimistic.

## Deploy to Hugging Face Spaces

1. Create a Space at <https://huggingface.co/new-space>: SDK **Gradio**, hardware **CPU basic (free)**.
2. Push this repository to it:
   ```bash
   git remote add space https://huggingface.co/spaces/<your-username>/EvidenceGuard-AI
   git 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 report
and in the app's About tab.

## Licence

Code: Apache-2.0. Generated documents and questions: synthetic, free to reuse with the "synthetic" label kept.