File size: 17,148 Bytes
2ab2b76 | 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 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 | """
scripts/build_report.py
-----------------------
Generate the 2–4 page technical report PDF (`report/technical_report.pdf`)
directly from verified repository artifacts (classifier_comparison.json,
e2e_results.jsonl, retest_results.jsonl, voice_4_records.json) using PyMuPDF Story.
"""
from __future__ import annotations
import json
from pathlib import Path
import pymupdf
from src.config import (
CLASSIFIER_COMPARISON_PATH,
E2E_RESULTS_PATH,
REPORT_DIR,
RETEST_RESULTS_PATH,
VOICE_RECORDS_JSON_PATH,
)
from src.evaluation.metrics import compute_aggregates
def _load_jsonl(path: Path) -> list[dict]:
return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
def _mean_gen_latency(records: list[dict]) -> float:
vals = [r.get("generator_latency_ms", 0.0) for r in records if r.get("generator_latency_ms")]
return round((sum(vals) / len(vals)) / 1000.0, 1) if vals else 0.0
def build_report(output_pdf: Path | None = None) -> Path:
REPORT_DIR.mkdir(parents=True, exist_ok=True)
out_path = output_pdf or (REPORT_DIR / "technical_report.pdf")
cmp_data = json.loads(CLASSIFIER_COMPARISON_PATH.read_text(encoding="utf-8"))
base_cls = cmp_data["baseline"]
enc_cls = cmp_data["fine_tuned_encoder"]
e2e_records = _load_jsonl(E2E_RESULTS_PATH)
e2e_agg = compute_aggregates(e2e_records)["metrics"]
e2e_lat_s = _mean_gen_latency(e2e_records)
retest_records = _load_jsonl(RETEST_RESULTS_PATH) if RETEST_RESULTS_PATH.exists() else []
has_retest = len(retest_records) == 24
if has_retest:
retest_agg = compute_aggregates(retest_records)["metrics"]
retest_lat_s = _mean_gen_latency(retest_records)
else:
retest_agg = None
retest_lat_s = 0.0
voice_records = json.loads(VOICE_RECORDS_JSON_PATH.read_text(encoding="utf-8"))
base_cited = sum(1 for r in e2e_records if r.get("cited_passage_ids"))
retest_cited = sum(1 for r in retest_records if r.get("cited_passage_ids"))
if retest_agg is not None:
retest_rows_html = f"""
<tr>
<td><strong>Post-Fix Retest</strong> (<code>retest_results.jsonl</code>, <code>Qwen2.5-1.5B-Instruct</code>)</td>
<td>{retest_agg['evidence_recall_at_3']['score']:.4f} (20/20)</td>
<td>{retest_cited}/{len(retest_records)} ({retest_cited/len(retest_records):.1%})</td>
<td>{retest_agg['supported_answers']['count']}/{retest_agg['supported_answers']['denominator']} ({retest_agg['supported_answers']['rate']:.1%})</td>
<td>{retest_agg['handling_unknowns']['count']}/{retest_agg['handling_unknowns']['denominator']} ({retest_agg['handling_unknowns']['rate']:.1%})</td>
<td>{retest_agg['consistency_across_languages']['count']}/{retest_agg['consistency_across_languages']['denominator']} ({retest_agg['consistency_across_languages']['rate']:.1%})</td>
<td>~{retest_lat_s}s</td>
</tr>"""
else:
retest_rows_html = """
<tr>
<td colspan="7"><em>Retest outputs not yet generated.</em></td>
</tr>"""
html = f"""
<!DOCTYPE html>
<html>
<head>
<style>
body {{
font-family: Helvetica, Arial, sans-serif;
font-size: 9.5pt;
line-height: 1.38;
color: #1f2937;
}}
h1 {{
font-size: 16pt;
color: #0f172a;
margin-bottom: 2pt;
border-bottom: 1.5pt solid #1d4ed8;
padding-bottom: 4pt;
}}
.subtitle {{
font-size: 9.5pt;
color: #475569;
margin-bottom: 10pt;
}}
h2 {{
font-size: 11.5pt;
color: #1e3a8a;
margin-top: 11pt;
margin-bottom: 4pt;
border-bottom: 0.5pt solid #cbd5e1;
padding-bottom: 2pt;
}}
h3 {{
font-size: 10pt;
color: #0f172a;
margin-top: 7pt;
margin-bottom: 2pt;
}}
p {{
margin-top: 2pt;
margin-bottom: 5pt;
text-align: justify;
}}
ul {{
margin-top: 2pt;
margin-bottom: 6pt;
padding-left: 15pt;
}}
li {{
margin-bottom: 2.5pt;
}}
table {{
width: 100%;
border-collapse: collapse;
margin-top: 4pt;
margin-bottom: 8pt;
font-size: 8.5pt;
}}
th, td {{
border: 0.6pt solid #cbd5e1;
padding: 4pt 5pt;
text-align: left;
vertical-align: top;
}}
th {{
background-color: #eff6ff;
color: #1e3a8a;
font-weight: bold;
}}
code {{
font-family: Courier, monospace;
font-size: 8.2pt;
background-color: #f1f5f9;
padding: 0.5pt 2pt;
}}
.callout {{
background-color: #f8fafc;
border-left: 3pt solid #1d4ed8;
padding: 5pt 8pt;
margin: 6pt 0;
font-size: 9pt;
}}
</style>
</head>
<body>
<h1>CampusDesk AI: Technical Design & Evaluation Report</h1>
<div class="subtitle">
Bilingual (English & Nigerian Pidgin) Voice-Enabled Campus Bursary Helpdesk for Zaria Institute of Technology (ZIT)
</div>
<h2>1. System Scope & Core Architecture</h2>
<p>
CampusDesk AI answers student questions on ZIT bursary deadlines, eligibility, required documents, and grant/fee schedules
across <strong>9 synthetic official sources</strong> (8 PDF notices <code>N01</code>–<code>N08</code> and 1 CSV fee table <code>N09</code>)
segmented into <strong>17 immutable section/row passages</strong> (<code>N01-P01</code> through <code>N09-R06</code>).
The pipeline runs <code>QueryPlanner → IntentClassifier → HybridRetriever → AmendmentResolver → GroundedGenerator → CitationValidator</code>,
preceded for spoken queries by local Whisper ASR (<code>openai/whisper-small</code>) feeding an editable verification textbox in Gradio.
</p>
<h2>2. Key Design Choice: Hybrid Retrieval with Soft Intent Bonus & Sub-Query Fusion</h2>
<p>
Student bursary queries frequently combine two intents in one turn (e.g., <em>"I fit still apply on 12 June 2026? Which papers every normal applicant gats attach?"</em>
merges <code>deadlines</code> and <code>required_documents</code>, while lost-ID queries span PDF <code>N01-P02</code> and CSV <code>N09-R03</code>).
We rejected <strong>hard intent filtering</strong> (which would silently drop cross-intent passages when only one primary intent is predicted) and <strong>single-vector retrieval alone</strong>
(which misses exact Naira amounts, notice IDs, and Nigerian Pidgin surface forms). Instead, <code>HybridRetriever</code> executes:
</p>
<ul>
<li><strong>Clause-Level Sub-Query Fusion:</strong> <code>QueryPlanner</code> decomposes multi-part queries and max-pools passage scores across the full query and each sub-clause.</li>
<li><strong>Hybrid Scoring:</strong> Normalized weighted sum of multilingual dense cosine similarity (<code>intfloat/multilingual-e5-small</code>, weight <code>0.62</code>) and lexical <code>BM25Okapi</code> (weight <code>0.38</code>).</li>
<li><strong>Soft Intent Bonus (+0.08):</strong> Gently boosts passages matching the predicted intent without excluding complementary documents, plus deterministic metadata amendment resolution (<code>N02 → N01</code> deadline change, <code>N04 → N03</code> Engineering/Computing/Vocational CGPA drop from <code>2.50</code> to <code>2.20</code>).</li>
</ul>
<div class="callout">
<strong>Measured Impact:</strong> Across all 20 answerable and partly-answerable held-out prompts (10 English + 10 Nigerian Pidgin),
<strong>Evidence Recall@3 reached 1.0000 (100%)</strong>, successfully surfacing both base notices and superseding amendments in top-3.
</div>
<h2>3. Intent Classification: TF-IDF Baseline vs. Fine-Tuned Afro-XLM-R</h2>
<p>
To prevent paraphrase leakage across splits, the 136-request bilingual dataset (68 English, 68 Nigerian Pidgin; 34 per intent)
was partitioned by <strong>request family</strong> (64 distinct families: <code>88 train / 24 val / 24 test</code>, strictly <strong>0 family overlap</strong> across splits).
We compared a tuned TF-IDF + LogisticRegression baseline against fine-tuned <code>Davlan/afro-xlmr-small</code> (seed 42):
</p>
<table>
<tr>
<th>Model</th>
<th>Selected Configuration</th>
<th>Val Macro-F1</th>
<th>Test Macro-F1</th>
<th>Latency / Query</th>
<th>Test Confusions (n=24)</th>
</tr>
<tr>
<td><strong>TF-IDF + LogisticRegression</strong></td>
<td><code>char_wb</code> n-grams, <code>C=2.0</code></td>
<td>{base_cls['val_macro_f1']:.4f}</td>
<td>{base_cls['test_macro_f1']:.4f}</td>
<td>{base_cls['test_latency_ms_per_query']:.3f} ms</td>
<td>2 (<code>REQ-031</code>, <code>REQ-032</code>)</td>
</tr>
<tr>
<td><strong>Fine-Tuned Afro-XLM-R</strong></td>
<td><code>Davlan/afro-xlmr-small</code>, <code>lr=5e-5</code>, 8 epochs</td>
<td>{enc_cls['val_macro_f1']:.4f}</td>
<td>{enc_cls['test_macro_f1']:.4f}</td>
<td>{enc_cls['test_latency_ms_per_query']:.3f} ms</td>
<td>0 (checkpoint reload verified)</td>
</tr>
</table>
<p>
Both baseline errors occurred on bilingual paraphrases of the same temporal validity boundary (<em>"How recent must an LGA indigency letter be before submission?"</em> / Pidgin equivalent),
which surface-matched <code>required_documents</code> vocabulary (<em>"LGA indigency letter", "upload"</em>) rather than <code>deadlines</code>. <code>Afro-XLM-R</code> resolved both cleanly.
</p>
<h2 style="page-break-before: always;">4. End-to-End Evaluation, Baseline Failures, & Post-Fix Retest</h2>
<p>
All 24 held-out prompts (12 pairs × 2 languages: 5 direct, 3 two-source/amendment, 2 partly answerable, 2 unanswerable) were audited with manual per-case judgements.
Baseline (<code>Qwen2.5-0.5B-Instruct</code>) and post-fix retest (<code>Qwen2.5-1.5B-Instruct</code> + prompt/context fixes) outputs are stored and scored separately:
</p>
<table style="page-break-inside: avoid;">
<tr>
<th>Run Label (Artifact Path)</th>
<th>Recall@3</th>
<th>Non-Empty Citations</th>
<th>Supported Answers</th>
<th>Handling Unknowns</th>
<th>Cross-Lang Consistency</th>
<th>Mean Gen Latency</th>
</tr>
<tr>
<td><strong>Initial Baseline</strong> (<code>e2e_results.jsonl</code>, <code>Qwen2.5-0.5B-Instruct</code>)</td>
<td>{e2e_agg['evidence_recall_at_3']['score']:.4f} (20/20)</td>
<td>{base_cited}/{len(e2e_records)} ({base_cited/len(e2e_records):.1%})</td>
<td>{e2e_agg['supported_answers']['count']}/{e2e_agg['supported_answers']['denominator']} ({e2e_agg['supported_answers']['rate']:.1%})</td>
<td>{e2e_agg['handling_unknowns']['count']}/{e2e_agg['handling_unknowns']['denominator']} ({e2e_agg['handling_unknowns']['rate']:.1%})</td>
<td>{e2e_agg['consistency_across_languages']['count']}/{e2e_agg['consistency_across_languages']['denominator']} ({e2e_agg['consistency_across_languages']['rate']:.1%})</td>
<td>~{e2e_lat_s}s</td>
</tr>
{retest_rows_html}
</table>
<h3>Three Observed Failures / Fragile Cases & First Next Fixes</h3>
<ul>
<li>
<strong>Failure 1 — Pidgin JSON & Citation Collapse (<code>P01-PCM</code>, <code>P06-PCM</code>) & 240-Token Cutoff (<code>P03-EN</code>, <code>P08-EN</code>):</strong>
<code>Qwen2.5-0.5B-Instruct</code> failed to obey the JSON schema on 17/24 prompts (only 7/24 non-empty citations; 10/12 Pidgin prompts emitted plain-text <code>Next Steps:</code> lists with <code>cited_passage_ids=[]</code>).
<em>Fix applied:</em> Upgraded to <code>Qwen2.5-1.5B-Instruct</code>, lifting valid citations to <strong>20/24 (83.3%)</strong> and doubling Supported Answers (20.0% → 40.0%). Two long answers (<code>P03-EN</code>, <code>P08-EN</code>) still clipped just before the closing brace at <code>max_new_tokens=240</code>, so runtime <code>max_new_tokens</code> in <code>answer_generator.py</code> was raised to <code>320</code>.
<em>Next engineering change:</em> Pair constrained JSON decoding with dedicated Pidgin few-shot examples or CUDA <code>Qwen2.5-3B-Instruct</code> so Pidgin queries retain Pidgin register rather than falling back to English prose.
</li>
<li>
<strong>Failure 2 — Evidence Negation Reversal & Amendment Date Blindness (<code>P05-EN</code>, <code>P06-EN</code>):</strong>
Despite retrieving <code>N05-P01</code> (Rank #1) and <code>N02-P01</code> (Rank #2), the <code>0.5B</code> baseline answered <em>"Yes"</em> to using a father's bank account (<code>P05-EN</code>) and applying on 12 June (<code>P06-EN</code>).
<em>Fix applied:</em> Moved <code>AMENDMENT RESOLUTION NOTES</code> to the <strong>top</strong> of the evidence block and added explicit prohibition/date rules. This fully resolved <code>P05-EN</code>/<code>P05-PCM</code> (now correctly rejecting parent accounts with <code>[N05-P01]</code>), while <code>1.5B</code> still failed the <code>12 June > 10 June</code> comparison on <code>P06</code> despite citing <code>N02-P01</code>.
<em>Next engineering change:</em> Add deterministic date-comparison helper checks in <code>AmendmentResolver</code> so expired deadlines inject an explicit <code>DEADLINE_EXPIRED=True</code> guard flag.
</li>
<li>
<strong>Failure 3 — Unanswerable Guessing (<code>P09</code>, <code>P11</code>) & Whisper Pidgin Negation Flip (<code>V04</code>):</strong>
Both <code>0.5B</code> and <code>1.5B</code> frequently guessed assertive <em>"No"</em>/<em>"cannot"</em> or fabricated appeal rules on silent policies (1/8 on <code>Handling Unknowns</code>). Separately, across {len(voice_records)} Whisper ASR fixtures (<code>voice_4_records.json</code>), English queries transcribed cleanly (<code>V01</code>, <code>V03</code>), but on Nigerian Pidgin <code>V04</code>, <code>openai/whisper-small</code> turned <em>"if deadline <strong>don pass</strong>"</em> (already passed) into <em>"if deadline <strong>don't pass</strong>"</em> (not passed).
<em>Next engineering change:</em> Retain mandatory editable-transcript verification before pipeline execution and add retrieval-margin abstention rules before invoking the causal LM on out-of-scope queries.
</li>
</ul>
<h2>5. Privacy & Observed Trade-Off</h2>
<p>
<strong>Privacy Note (Verified Against Code):</strong> All spoken inputs in <code>app.py</code> and <code>src/speech/transcription.py</code> execute locally via Whisper into an editable verification box and call <code>Path.unlink()</code> immediately after transcription (<code>delete_after=True</code>, covered by <code>test_speech_privacy_deletes_temp_audio_and_handles_silence</code>). Live queries remain strictly in memory; all notices, fee schedules, and Nigerian-accented neural TTS fixtures (<code>evaluation/voice_records/</code>) use fictional ZIT scenarios with zero student PII.
</p>
<p>
<strong>Core Trade-Off — CPU Inference Latency vs. Grounding Fidelity:</strong> While <code>TF-IDF</code> is ~577× faster than <code>Afro-XLM-R</code> (0.1 ms vs. 55.4 ms, negligible next to RAG), swapping the generator from <code>Qwen2.5-0.5B</code> (~{e2e_lat_s}s/query on CPU) to <code>Qwen2.5-1.5B</code> (~{retest_lat_s}s/query on CPU, ~5.4× slower) trades higher CPU latency (and requires two-stage memory unloading in batch evaluation to stay within ~3.1 GB RAM) for nearly 3× higher verified citation compliance (7/24 → 20/24), 2× Supported Answers (20.0% → 40.0%), and 3× Cross-Language consistency (8.3% → 25.0%). Setting <code>CAMPUSDESK_GEN_MODEL</code> or running on CUDA (<code>Qwen2.5-3B-Instruct</code>) removes the CPU latency bottleneck in deployment.
</p>
</body>
</html>
"""
story = pymupdf.Story(html=html)
mediabox = pymupdf.paper_rect("a4")
where = mediabox + (36, 36, -36, -36)
writer = pymupdf.DocumentWriter(str(out_path))
more = True
while more:
device = writer.begin_page(mediabox)
more, _ = story.place(where)
story.draw(device, pymupdf.Identity)
writer.end_page()
writer.close()
doc = pymupdf.open(str(out_path))
page_count = len(doc)
doc.close()
print(f"Generated technical report PDF: {out_path} ({page_count} pages)")
return out_path
if __name__ == "__main__":
build_report()
|