--- language: - en - pcm license: mit tags: - rag - retrieval-augmented-generation - intent-classification - nigerian-pidgin - multilingual - gradio - bursary - afro-xlmr --- # CampusDesk AI — Bilingual & Voice Campus Bursary Helpdesk (ZIT) CampusDesk AI is an end-to-end **bilingual (English & Nigerian Pidgin)**, voice-enabled Retrieval-Augmented Generation (RAG) assistant built for the fictional **Zaria Institute of Technology (ZIT) Student Bursary & Welfare Office**. It combines intent classification (`TF-IDF + LogisticRegression` vs. fine-tuned `Davlan/afro-xlmr-small`), hybrid dense + lexical passage retrieval with sub-query fusion, deterministic amendment resolution (`N02` -> `N01`, `N04` -> `N03`), citation validation, and local Whisper speech transcription in a Gradio web application. --- ## Architecture Overview ```text User Query (Text or Voice Audio via Whisper ASR -> Editable Transcript Box) │ ▼ [1. Query Planner] src/pipeline/query_planner.py │ ├─ Bilingual cue detection (English / Nigerian Pidgin) │ └─ Multi-part clause splitter (full query + sub-queries) ▼ [2. Intent Classifier] src/classification/classifier.py │ ├─ Baseline: TF-IDF (char_wb, C=2.0) + LogisticRegression │ └─ Encoder: Fine-tuned Davlan/afro-xlmr-small (4 intents) ▼ [3. Hybrid Retriever] src/retrieval/retriever.py │ ├─ Dense: intfloat/multilingual-e5-small (cosine over passage_embeddings.npz) │ ├─ Lexical: BM25Okapi (bm25_corpus.json) │ └─ Rerank: 0.62*dense + 0.38*BM25 + 0.08*intent_bonus (max-pooled sub-queries, top-3) ▼ [4. Amendment Resolver] src/amendments/resolver.py │ └─ Isolates latest dated amendments (N02->N01 deadline, N04->N03 CGPA) without clobbering unamended rules ▼ [5. Grounded Generator] src/generation/answer_generator.py │ └─ Qwen2.5-1.5B-Instruct (CPU) / Qwen2.5-3B-Instruct (CUDA) -> JSON {answer, next_steps, missing_information, cited_passage_ids} ▼ [6. Citation Validator] src/grounding/citation_validator.py └─ Strips hallucinated passage IDs, syncs inline [PASSAGE_ID] tags, suppresses ungrounded next_steps ``` --- ## Directory Structure ```text capstone/ ├── data/ │ ├── raw/pdf/ # 8 synthetic ZIT bursary PDF notices (N01–N08) │ ├── raw/csv/ # bursary_fees_and_tiers.csv (N09) │ ├── processed/passages.jsonl # 17 deterministic section/row passages (N01-P01 .. N09-R06) │ ├── manifests/source_manifest.csv │ └── intent_dataset.csv # 136 bilingual requests across 64 families (88 train / 24 val / 24 test) ├── notebooks/ # Reproducible experiment notebooks (run 01 -> 04) │ ├── 01_dataset_preparation.ipynb │ ├── 02_baseline_training.ipynb │ ├── 03_encoder_finetuning.ipynb │ └── 04_model_evaluation.ipynb ├── artifacts/ │ ├── baseline/tfidf_baseline.joblib │ ├── fine_tuned/ # Saved Davlan/afro-xlmr-small checkpoint + tokenizer │ ├── label_map.json │ └── classifier_comparison.json ├── indexes/ │ ├── passage_embeddings.npz # Multilingual-E5 embeddings │ └── bm25_corpus.json # BM25 tokenized index ├── src/ │ ├── config.py # Central paths & pinned model IDs │ ├── schemas.py # Pydantic contracts across pipeline stages │ ├── classification/ # classifier.py, model_loader.py │ ├── document_processing/ # extractors.py, chunker.py, index_builder.py │ ├── retrieval/ # bm25.py, semantic.py, reranker.py, retriever.py │ ├── amendments/ # resolver.py │ ├── generation/ # answer_generator.py │ ├── speech/ # transcription.py (Whisper ASR + silence/error fallback) │ ├── grounding/ # citation_validator.py │ ├── pipeline/ # query_planner.py, orchestrator.py │ └── evaluation/ # metrics.py ├── evaluation/ │ ├── gold_answers.json # 12 held-out bilingual evaluation pairs (24 prompts) │ ├── test_scenarios.csv │ ├── actual_outputs/e2e_results.jsonl │ ├── retest_outputs/retest_results.jsonl │ ├── voice_records/ # 4 synthetic spoken Nigerian-accented WAVs + voice_4_records.json │ ├── failure_traces.md │ └── recompute_metrics.py ├── tests/ # Unit & integration tests (pytest) ├── scripts/ # Corpus, dataset, training, index, voice, and eval CLI runners ├── report/technical_report.pdf # 2–4 page technical report ├── app.py # Gradio web UI └── requirements.txt ``` --- ## Quick Start ### 1. Environment Setup (Windows PowerShell) ```powershell python -m venv .venv .venv\Scripts\pip.exe install -r requirements.txt Copy-Item .env.example .env ``` ### 2. Full Pipeline Rebuild (Corpus -> Classifiers -> Index -> App) ```powershell .venv\Scripts\python.exe -m scripts.build_corpus .venv\Scripts\python.exe -m scripts.build_intent_dataset .venv\Scripts\python.exe -m scripts.train_classifiers .venv\Scripts\python.exe -m scripts.build_index .venv\Scripts\python.exe app.py ``` Open the local Gradio URL shown in the terminal (typically `http://127.0.0.1:7860`). ### 3. Rebuilding Indexes After Corpus Edits ```powershell .venv\Scripts\python.exe -m scripts.build_index ``` This regenerates `indexes/passage_embeddings.npz` and `indexes/bm25_corpus.json` from `data/processed/passages.jsonl`. ### 4. Notebook Execution Order Run the notebooks sequentially inside `notebooks/`: 1. `01_dataset_preparation.ipynb` — corpus hygiene, family-grouped split verification, dataset audit 2. `02_baseline_training.ipynb` — TF-IDF + LogisticRegression tuning on validation set 3. `03_encoder_finetuning.ipynb` — `Davlan/afro-xlmr-small` fine-tuning & checkpoint reload verification 4. `04_model_evaluation.ipynb` — held-out bilingual test metrics & failure inspection ### 5. Loading the Saved Fine-Tuned Checkpoint Programmatically ```python from src.classification.classifier import EncoderIntentClassifier clf = EncoderIntentClassifier() # loads artifacts/fine_tuned/ and artifacts/label_map.json pred = clf.predict("I fit still apply on 12 June 2026? Which papers I need carry?") print(pred.label, pred.confidence, pred.probabilities) ``` --- ## Evaluation & Tests ### Intent Classification Results (`artifacts/classifier_comparison.json`) Dataset: 136 requests across 64 families (`88 train / 24 val / 24 test`, zero family overlap across splits, balanced 4 intents x 6 test examples). | Model | Settings | Val Macro-F1 | Test Macro-F1 | Latency / Query | Confused Test Cases | |---|---|---:|---:|---:|---:| | **TF-IDF + LogisticRegression (Baseline)** | `char_wb`, `C=2.0` | `0.8325` | `0.9143` | `0.096 ms` | 2 (`REQ-031`, `REQ-032`) | | **Fine-Tuned `Davlan/afro-xlmr-small`** | `lr=5e-5`, `8 epochs`, `seed=42` | `1.0000` | `1.0000` | `55.436 ms` | 0 | ### End-to-End Bilingual Evaluation (24 Held-Out Prompts) | Run (Artifact Path) | Evidence Recall@3 | Non-Empty Citations | Supported Answers | Handling Unknowns | Cross-Language Consistency | |---|---:|---:|---:|---:|---:| | **Baseline (`Qwen2.5-0.5B-Instruct`)** (`evaluation/actual_outputs/e2e_results.jsonl`) | `1.0000` (20/20) | `7/24` (`29.2%`) | `4/20` (`20.0%`) | `1/8` (`12.5%`) | `1/12` (`8.3%`) | | **Post-Fix Retest (`Qwen2.5-1.5B-Instruct`)** (`evaluation/retest_outputs/retest_results.jsonl`) | `1.0000` (20/20) | `20/24` (`83.3%`) | `8/20` (`40.0%`) | `1/8` (`12.5%`) | `3/12` (`25.0%`) | ### Running Tests, Recomputing Metrics & Rebuilding Report ```powershell .venv\Scripts\pytest.exe -v .venv\Scripts\python.exe -m evaluation.recompute_metrics --input evaluation\actual_outputs\e2e_results.jsonl .venv\Scripts\python.exe -m evaluation.recompute_metrics --input evaluation\retest_outputs\retest_results.jsonl .venv\Scripts\python.exe -m scripts.build_report ``` ### Sample Bilingual Test Queries - **English (Two-Source + Amendment):** `"Can I still apply on 12 June 2026, and which documents must every standard applicant attach?"` - **Nigerian Pidgin (Two-Source + Amendment):** `"I fit still apply on 12 June 2026? Which papers every normal applicant gats attach?"` - **English (Eligibility Amendment):** `"I am a full-time 300-level Engineering student with a 2.35 CGPA and no external scholarship. Am I eligible to apply?"` - **Nigerian Pidgin (Fee + Document Cross-Format):** `"If my ZIT Student ID card don loss before I apply, wetin I go do and how much I go pay for replacement, and which other compulsory papers I need?"` --- ## Privacy & Safe-Testing Policy - **Voice Audio Privacy (`delete_after=True`):** Uploaded or recorded voice audio is transcribed locally via `openai/whisper-small` into an **editable text box** (so students can verify dates, numbers, and Pidgin negation before retrieval) and the temporary audio file is deleted immediately after transcription (`src/speech/transcription.py`, verified by `test_speech_privacy_deletes_temp_audio_and_handles_silence`). - **No Disk Persistence of Live Queries:** Live user queries and transcripts stay strictly in memory during the active Gradio session. - **Zero Real PII:** All notices, fee schedules, and voice fixtures (`evaluation/voice_records/`, generated via Nigerian-accented neural TTS) use fictional Zaria Institute of Technology (ZIT) data.