campusdesk-ai / app.py
Estarcode's picture
Upload folder using huggingface_hub
2ab2b76 verified
Raw History Blame Contribute Delete
8.29 kB
"""CampusDesk AI — Gradio Bilingual & Voice Campus Bursary Helpdesk."""
import json
from typing import Tuple
import gradio as gr
from src.config import DEFAULT_DEPLOYED_CLASSIFIER, LANGUAGE_CHOICES
from src.pipeline.orchestrator import answer_question
from src.speech.transcription import get_transcriber
PRIVACY_NOTICE = (
"**Privacy & Safe-Testing Notice:** Voice notes recorded or uploaded in this app are "
"transcribed using local Whisper ASR into the editable text box and the temporary audio file "
"is deleted immediately after transcription (`delete_after=True`). Live queries and transcripts "
"are held only in memory for your active session and are never persisted to disk. All bursary "
"notices, student figures, and evaluation recordings use fictional ZIT test scenarios."
)
def handle_transcribe(audio_filepath: str) -> Tuple[str, str]:
transcriber = get_transcriber()
transcript, status_msg, _ = transcriber.transcribe(audio_filepath, delete_after=True)
return transcript, status_msg
def handle_ask(
question_text: str,
reply_language: str,
classifier_choice: str,
) -> Tuple[str, str, str, str, str]:
if not question_text or not question_text.strip():
return "⚠️ Please type your question or transcribe a voice note first.", "", "", "", ""
resp = answer_question(
query=question_text,
reply_language=reply_language,
classifier_choice=classifier_choice,
)
lines = [f"### Answer ({resp.reply_language})\n", resp.grounded.answer]
if resp.grounded.next_steps:
lines.append("\n### Next Steps Checklist")
for step in resp.grounded.next_steps:
lines.append(f"- [ ] {step}")
if resp.grounded.missing_information and resp.grounded.missing_information.lower() != "none":
lines.append(f"\n> **Missing / Unsettled Information:** {resp.grounded.missing_information}")
if resp.grounded.cited_passage_ids:
lines.append(
f"\n**Cited Passages:** {', '.join(f'`{cid}`' for cid in resp.grounded.cited_passage_ids)}"
)
if resp.grounded.citation_warnings:
lines.append(f"\n*Grounding validator note:* {'; '.join(resp.grounded.citation_warnings)}")
answer_md = "\n".join(lines)
trace_lines = [
f"- **Classifier Used:** `{resp.intent.model_used}`",
f"- **Predicted Intent:** `{resp.intent.label}` (confidence: `{resp.intent.confidence:.2%}`, `{resp.intent.latency_ms:.1f} ms`)",
f"- **Query Plan:** multi-part=`{resp.query_plan.is_multipart}`, detected_hint=`{resp.query_plan.detected_language_hint}`, subqueries=`{resp.query_plan.subqueries}`",
f"- **Intent Probabilities:** `{json.dumps({k: round(v, 3) for k, v in resp.intent.probabilities.items()})}`",
f"- **Total Pipeline Latency:** `{resp.total_latency_ms:.0f} ms` (Generator: `{resp.grounded.latency_ms:.0f} ms`)",
"\n**Top-3 Retrieved Passages (Hybrid Dense + BM25 + Soft Intent Bonus):**",
]
for rp in resp.top_passages:
trace_lines.append(
f"{rp.rank}. **`{rp.passage.passage_id}`** ({rp.passage.doc_id}, {rp.passage.date}) — "
f"total=`{rp.score:.3f}` [dense=`{rp.dense_score:.3f}`, lexical=`{rp.lexical_score:.3f}`, intent_bonus=`{rp.intent_bonus:.3f}`]"
)
if resp.amendment_notes:
trace_lines.append("\n**Amendment Resolution Applied:**")
for note in resp.amendment_notes:
trace_lines.append(f"- {note}")
trace_md = "\n".join(trace_lines)
passage_cards = []
for rp in resp.top_passages:
p = rp.passage
is_cited = p.passage_id in resp.grounded.cited_passage_ids
badge = "✅ CITED IN ANSWER" if is_cited else "Retrieved (Top-3)"
amend_line = f"\n**Amends:** `{p.amends_doc_id}` — {p.amends_scope}" if p.amends_doc_id else ""
passage_cards.append(
f"#### [{p.passage_id}] {p.title} — *{badge}*\n"
f"**Format:** `{p.format.upper()}` | **Date:** `{p.date}` | **Version:** `{p.version}` | "
f"**Location:** `{p.section_or_row}`{amend_line}\n\n"
f"> {p.text}"
)
while len(passage_cards) < 3:
passage_cards.append("No passage retrieved in this slot.")
return answer_md, trace_md, passage_cards[0], passage_cards[1], passage_cards[2]
def build_demo() -> gr.Blocks:
with gr.Blocks(title="CampusDesk AI — ZIT Bursary Helpdesk") as demo:
gr.Markdown(
"# CampusDesk AI — Zaria Institute of Technology (ZIT) Bursary Helpdesk\n"
"Bilingual (**English & Nigerian Pidgin**) grounded assistant backed by official ZIT PDF notices and fee CSV schedules."
)
with gr.Row():
with gr.Column(scale=5):
audio_in = gr.Audio(
sources=["microphone", "upload"],
type="filepath",
format="wav",
label="1. Optional Voice Note (English or Nigerian Pidgin)",
)
transcribe_btn = gr.Button("Transcribe Voice to Editable Box", variant="secondary")
asr_status = gr.Textbox(
label="Speech Diagnostics / Fallback Notice",
interactive=False,
value="Type below directly, or record/upload audio and click Transcribe.",
)
question_box = gr.Textbox(
label="2. Student Question (Review & Edit Transcript Before Submitting)",
placeholder="e.g. I fit still apply on 12 June 2026? Which paper I need carry?",
lines=3,
)
with gr.Row():
reply_lang = gr.Radio(
choices=LANGUAGE_CHOICES,
value="Nigerian Pidgin",
label="3. Reply Language",
)
clf_choice = gr.Radio(
choices=["encoder", "baseline"],
value=DEFAULT_DEPLOYED_CLASSIFIER,
label="Intent Classifier",
)
submit_btn = gr.Button("Ask CampusDesk AI", variant="primary")
gr.Examples(
examples=[
["I fit still apply on 12 June 2026? Which paper I need carry?", "Nigerian Pidgin"],
["I am a full-time 300-level Engineering student with a 2.35 CGPA and no outside scholarship. Am I eligible?", "English"],
["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?", "Nigerian Pidgin"],
["What is the final application closing date, and how can a student submit a late appeal if they missed it?", "English"],
["Bursary office dey refund hostel accommodation money for students wey dey stay off-campus during IT?", "Nigerian Pidgin"],
],
inputs=[question_box, reply_lang],
label="Sample Acceptance & Edge-Case Queries",
)
with gr.Column(scale=7):
answer_out = gr.Markdown(label="Grounded Guidance & Checklist")
with gr.Accordion("Pipeline Trace (Intent Prediction & Top-3 Retrieval Scores)", open=True):
trace_out = gr.Markdown()
with gr.Accordion("Open Exact Source Passages (Citations)", open=True):
p1_out = gr.Markdown()
gr.Markdown("---")
p2_out = gr.Markdown()
gr.Markdown("---")
p3_out = gr.Markdown()
gr.Markdown(f"---\n{PRIVACY_NOTICE}")
transcribe_btn.click(
fn=handle_transcribe,
inputs=[audio_in],
outputs=[question_box, asr_status],
)
submit_btn.click(
fn=handle_ask,
inputs=[question_box, reply_lang, clf_choice],
outputs=[answer_out, trace_out, p1_out, p2_out, p3_out],
)
return demo
if __name__ == "__main__":
demo = build_demo()
demo.launch(server_name="127.0.0.1", server_port=7860)