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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
def respond(
|
| 6 |
-
message,
|
| 7 |
-
history: list[dict[str, str]],
|
| 8 |
-
system_message,
|
| 9 |
-
max_tokens,
|
| 10 |
-
temperature,
|
| 11 |
-
top_p,
|
| 12 |
-
hf_token: gr.OAuthToken,
|
| 13 |
-
):
|
| 14 |
-
"""
|
| 15 |
-
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
|
| 16 |
-
"""
|
| 17 |
-
client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
|
| 18 |
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
|
| 28 |
-
messages,
|
| 29 |
-
max_tokens=max_tokens,
|
| 30 |
-
stream=True,
|
| 31 |
-
temperature=temperature,
|
| 32 |
-
top_p=top_p,
|
| 33 |
-
):
|
| 34 |
-
choices = message.choices
|
| 35 |
-
token = ""
|
| 36 |
-
if len(choices) and choices[0].delta.content:
|
| 37 |
-
token = choices[0].delta.content
|
| 38 |
|
| 39 |
-
response += token
|
| 40 |
-
yield response
|
| 41 |
|
|
|
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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gr.LoginButton()
|
| 65 |
-
chatbot.render()
|
| 66 |
-
|
| 67 |
-
|
| 68 |
if __name__ == "__main__":
|
| 69 |
demo.launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import List, Dict, Tuple
|
| 5 |
+
|
| 6 |
import gradio as gr
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from sentence_transformers import SentenceTransformer
|
| 10 |
+
|
| 11 |
+
# Optional document readers
|
| 12 |
+
from docx import Document
|
| 13 |
+
from pypdf import PdfReader
|
| 14 |
+
|
| 15 |
+
# ------------------------------------------------------------
|
| 16 |
+
# Configuration
|
| 17 |
+
# ------------------------------------------------------------
|
| 18 |
+
APP_TITLE = "MAIAD01 Teaching Plan Chatbot"
|
| 19 |
+
FAQ_FILE = "faq.csv"
|
| 20 |
+
TEACHING_PLAN_DIR = "teaching_plans"
|
| 21 |
+
|
| 22 |
+
EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
|
| 23 |
+
|
| 24 |
+
# FAQ answers are preferred because they are curated from the teaching plans.
|
| 25 |
+
FAQ_THRESHOLD = float(os.getenv("FAQ_THRESHOLD", "0.48"))
|
| 26 |
+
DOC_THRESHOLD = float(os.getenv("DOC_THRESHOLD", "0.24"))
|
| 27 |
+
|
| 28 |
+
CHUNK_WORDS = int(os.getenv("CHUNK_WORDS", "260"))
|
| 29 |
+
CHUNK_OVERLAP = int(os.getenv("CHUNK_OVERLAP", "45"))
|
| 30 |
+
|
| 31 |
+
# Generation is optional. For a faster and safer academic demo, keep this false.
|
| 32 |
+
# Set USE_GENERATOR=true in Hugging Face Space secrets/environment variables
|
| 33 |
+
# if you want Flan-T5 to summarise retrieved chunks.
|
| 34 |
+
USE_GENERATOR = os.getenv("USE_GENERATOR", "false").lower() == "true"
|
| 35 |
+
GENERATOR_MODEL = os.getenv("GENERATOR_MODEL", "google/flan-t5-small")
|
| 36 |
+
|
| 37 |
+
# ------------------------------------------------------------
|
| 38 |
+
# Utility functions
|
| 39 |
+
# ------------------------------------------------------------
|
| 40 |
+
def clean_text(text: str) -> str:
|
| 41 |
+
"""Normalise whitespace without changing academic content."""
|
| 42 |
+
if text is None:
|
| 43 |
+
return ""
|
| 44 |
+
return re.sub(r"\s+", " ", str(text).replace("\xa0", " ")).strip()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def safe_excerpt(text: str, max_chars: int = 1400) -> str:
|
| 48 |
+
text = clean_text(text)
|
| 49 |
+
if len(text) <= max_chars:
|
| 50 |
+
return text
|
| 51 |
+
return text[:max_chars].rsplit(" ", 1)[0] + "..."
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def parse_course_code_from_text(text: str) -> str:
|
| 55 |
+
match = re.search(r"\b[A-Z]{3}\d{4}\b", text or "")
|
| 56 |
+
return match.group(0) if match else ""
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def read_docx(path: Path) -> str:
|
| 60 |
+
"""Read paragraphs and tables from a DOCX teaching plan."""
|
| 61 |
+
doc = Document(str(path))
|
| 62 |
+
parts = []
|
| 63 |
+
|
| 64 |
+
for paragraph in doc.paragraphs:
|
| 65 |
+
text = clean_text(paragraph.text)
|
| 66 |
+
if text:
|
| 67 |
+
parts.append(text)
|
| 68 |
+
|
| 69 |
+
for table_index, table in enumerate(doc.tables, start=1):
|
| 70 |
+
parts.append(f"[Table {table_index}]")
|
| 71 |
+
for row in table.rows:
|
| 72 |
+
cells = [clean_text(cell.text) for cell in row.cells]
|
| 73 |
+
if any(cells):
|
| 74 |
+
parts.append(" | ".join(cells))
|
| 75 |
+
|
| 76 |
+
return "\n".join(parts)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def read_pdf(path: Path) -> str:
|
| 80 |
+
"""Read text-based PDF files. Scanned PDFs may require OCR, which is not included here."""
|
| 81 |
+
reader = PdfReader(str(path))
|
| 82 |
+
pages = []
|
| 83 |
+
for page_number, page in enumerate(reader.pages, start=1):
|
| 84 |
+
page_text = page.extract_text() or ""
|
| 85 |
+
if page_text.strip():
|
| 86 |
+
pages.append(f"[Page {page_number}] {page_text}")
|
| 87 |
+
return "\n".join(pages)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def read_txt(path: Path) -> str:
|
| 91 |
+
return path.read_text(encoding="utf-8", errors="ignore")
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def read_supported_file(path: Path) -> str:
|
| 95 |
+
suffix = path.suffix.lower()
|
| 96 |
+
if suffix == ".docx":
|
| 97 |
+
return read_docx(path)
|
| 98 |
+
if suffix == ".pdf":
|
| 99 |
+
return read_pdf(path)
|
| 100 |
+
if suffix in [".txt", ".md", ".csv"]:
|
| 101 |
+
return read_txt(path)
|
| 102 |
+
return ""
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def infer_course_title_from_faq(faq_df: pd.DataFrame, course_code: str) -> str:
|
| 106 |
+
if not course_code or faq_df.empty:
|
| 107 |
+
return ""
|
| 108 |
+
rows = faq_df[faq_df["course_code"].astype(str).str.upper() == course_code.upper()]
|
| 109 |
+
if not rows.empty:
|
| 110 |
+
return str(rows.iloc[0].get("course_title", "")).strip()
|
| 111 |
+
return ""
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def chunk_text(text: str, source_file: str, course_code: str, course_title: str) -> List[Dict]:
|
| 115 |
+
"""Split a document into overlapping chunks for semantic search."""
|
| 116 |
+
words = clean_text(text).split()
|
| 117 |
+
chunks = []
|
| 118 |
+
start = 0
|
| 119 |
+
chunk_id = 1
|
| 120 |
+
|
| 121 |
+
while start < len(words):
|
| 122 |
+
end = start + CHUNK_WORDS
|
| 123 |
+
chunk = " ".join(words[start:end])
|
| 124 |
+
if len(chunk) > 120:
|
| 125 |
+
chunks.append({
|
| 126 |
+
"chunk_id": f"{course_code or 'DOC'}-{chunk_id:04d}",
|
| 127 |
+
"course_code": course_code,
|
| 128 |
+
"course_title": course_title,
|
| 129 |
+
"source_file": source_file,
|
| 130 |
+
"text": chunk
|
| 131 |
+
})
|
| 132 |
+
chunk_id += 1
|
| 133 |
+
|
| 134 |
+
if end >= len(words):
|
| 135 |
+
break
|
| 136 |
+
start = max(0, end - CHUNK_OVERLAP)
|
| 137 |
+
|
| 138 |
+
return chunks
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# ------------------------------------------------------------
|
| 142 |
+
# Load FAQ
|
| 143 |
+
# ------------------------------------------------------------
|
| 144 |
+
def load_faq() -> pd.DataFrame:
|
| 145 |
+
path = Path(FAQ_FILE)
|
| 146 |
+
if not path.exists():
|
| 147 |
+
columns = [
|
| 148 |
+
"id", "course_code", "course_title", "category",
|
| 149 |
+
"student_question", "alternate_questions", "answer",
|
| 150 |
+
"source_file", "tags", "priority"
|
| 151 |
+
]
|
| 152 |
+
return pd.DataFrame(columns=columns)
|
| 153 |
+
|
| 154 |
+
df = pd.read_csv(path).fillna("")
|
| 155 |
+
required = [
|
| 156 |
+
"id", "course_code", "course_title", "category",
|
| 157 |
+
"student_question", "alternate_questions", "answer",
|
| 158 |
+
"source_file", "tags", "priority"
|
| 159 |
+
]
|
| 160 |
+
for col in required:
|
| 161 |
+
if col not in df.columns:
|
| 162 |
+
df[col] = ""
|
| 163 |
+
return df[required]
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
faq_df = load_faq()
|
| 167 |
+
|
| 168 |
+
# ------------------------------------------------------------
|
| 169 |
+
# Load teaching plan documents
|
| 170 |
+
# ------------------------------------------------------------
|
| 171 |
+
def load_teaching_plan_chunks() -> List[Dict]:
|
| 172 |
+
plan_dir = Path(TEACHING_PLAN_DIR)
|
| 173 |
+
if not plan_dir.exists():
|
| 174 |
+
return []
|
| 175 |
+
|
| 176 |
+
all_chunks = []
|
| 177 |
+
supported = [".docx", ".pdf", ".txt", ".md", ".csv"]
|
| 178 |
+
|
| 179 |
+
for path in sorted(plan_dir.iterdir()):
|
| 180 |
+
if not path.is_file() or path.suffix.lower() not in supported:
|
| 181 |
+
continue
|
| 182 |
+
|
| 183 |
+
text = read_supported_file(path)
|
| 184 |
+
if not text.strip():
|
| 185 |
+
continue
|
| 186 |
+
|
| 187 |
+
course_code = parse_course_code_from_text(path.name) or parse_course_code_from_text(text)
|
| 188 |
+
course_title = infer_course_title_from_faq(faq_df, course_code)
|
| 189 |
+
|
| 190 |
+
# Fallback title extraction for files not represented in FAQ
|
| 191 |
+
if not course_title:
|
| 192 |
+
title_match = re.search(r"Course Title:\s*\|?\s*([^\n|]+)", text, re.I)
|
| 193 |
+
course_title = clean_text(title_match.group(1)) if title_match else path.stem
|
| 194 |
+
|
| 195 |
+
all_chunks.extend(chunk_text(text, path.name, course_code, course_title))
|
| 196 |
+
|
| 197 |
+
return all_chunks
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
document_chunks = load_teaching_plan_chunks()
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------
|
| 203 |
+
# Build semantic indexes
|
| 204 |
+
# ------------------------------------------------------------
|
| 205 |
+
print("Loading embedding model...")
|
| 206 |
+
embedding_model = SentenceTransformer(EMBEDDING_MODEL)
|
| 207 |
+
|
| 208 |
+
def build_faq_search_texts(df: pd.DataFrame) -> List[str]:
|
| 209 |
+
texts = []
|
| 210 |
+
for _, row in df.iterrows():
|
| 211 |
+
texts.append(
|
| 212 |
+
" ".join([
|
| 213 |
+
str(row["course_code"]),
|
| 214 |
+
str(row["course_title"]),
|
| 215 |
+
str(row["category"]),
|
| 216 |
+
str(row["student_question"]),
|
| 217 |
+
str(row["alternate_questions"]),
|
| 218 |
+
str(row["tags"]),
|
| 219 |
+
safe_excerpt(str(row["answer"]), 450)
|
| 220 |
+
])
|
| 221 |
+
)
|
| 222 |
+
return texts
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
faq_search_texts = build_faq_search_texts(faq_df)
|
| 226 |
+
if faq_search_texts:
|
| 227 |
+
faq_embeddings = embedding_model.encode(faq_search_texts, normalize_embeddings=True)
|
| 228 |
+
else:
|
| 229 |
+
faq_embeddings = np.empty((0, 384))
|
| 230 |
+
|
| 231 |
+
doc_search_texts = [
|
| 232 |
+
" ".join([
|
| 233 |
+
chunk["course_code"],
|
| 234 |
+
chunk["course_title"],
|
| 235 |
+
chunk["source_file"],
|
| 236 |
+
chunk["text"]
|
| 237 |
+
])
|
| 238 |
+
for chunk in document_chunks
|
| 239 |
+
]
|
| 240 |
+
|
| 241 |
+
if doc_search_texts:
|
| 242 |
+
doc_embeddings = embedding_model.encode(doc_search_texts, normalize_embeddings=True)
|
| 243 |
+
else:
|
| 244 |
+
doc_embeddings = np.empty((0, 384))
|
| 245 |
|
| 246 |
+
# Optional generator
|
| 247 |
+
generator = None
|
| 248 |
+
if USE_GENERATOR:
|
| 249 |
+
try:
|
| 250 |
+
from transformers import pipeline
|
| 251 |
+
print(f"Loading generator model: {GENERATOR_MODEL}")
|
| 252 |
+
generator = pipeline(
|
| 253 |
+
"text2text-generation",
|
| 254 |
+
model=GENERATOR_MODEL,
|
| 255 |
+
max_new_tokens=220
|
| 256 |
+
)
|
| 257 |
+
except Exception as exc:
|
| 258 |
+
print(f"Generator could not be loaded. Falling back to retrieval-only mode. Error: {exc}")
|
| 259 |
+
generator = None
|
| 260 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
|
| 262 |
+
# ------------------------------------------------------------
|
| 263 |
+
# Course options and filtering
|
| 264 |
+
# ------------------------------------------------------------
|
| 265 |
+
def get_course_options() -> List[str]:
|
| 266 |
+
course_pairs = []
|
| 267 |
|
| 268 |
+
if not faq_df.empty:
|
| 269 |
+
for _, row in faq_df.iterrows():
|
| 270 |
+
code = str(row["course_code"]).strip()
|
| 271 |
+
title = str(row["course_title"]).strip()
|
| 272 |
+
if code and code.upper() != "ALL" and title:
|
| 273 |
+
course_pairs.append((code, title))
|
| 274 |
|
| 275 |
+
for chunk in document_chunks:
|
| 276 |
+
code = chunk.get("course_code", "").strip()
|
| 277 |
+
title = chunk.get("course_title", "").strip()
|
| 278 |
+
if code and title:
|
| 279 |
+
course_pairs.append((code, title))
|
| 280 |
|
| 281 |
+
unique = []
|
| 282 |
+
seen = set()
|
| 283 |
+
for code, title in course_pairs:
|
| 284 |
+
key = code.upper()
|
| 285 |
+
if key not in seen:
|
| 286 |
+
seen.add(key)
|
| 287 |
+
unique.append(f"{code} β {title}")
|
| 288 |
|
| 289 |
+
return ["All courses"] + unique
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
|
|
|
|
|
|
|
| 291 |
|
| 292 |
+
COURSE_OPTIONS = get_course_options()
|
| 293 |
|
| 294 |
+
|
| 295 |
+
def parse_selected_course(course_selection: str) -> str:
|
| 296 |
+
if not course_selection or course_selection == "All courses":
|
| 297 |
+
return "ALL"
|
| 298 |
+
match = re.match(r"([A-Z]{3}\d{4})", course_selection.strip())
|
| 299 |
+
return match.group(1).upper() if match else "ALL"
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def infer_course_from_question(question: str, selected_course: str) -> str:
|
| 303 |
+
selected_code = parse_selected_course(selected_course)
|
| 304 |
+
if selected_code != "ALL":
|
| 305 |
+
return selected_code
|
| 306 |
+
|
| 307 |
+
# Course code in the question takes priority.
|
| 308 |
+
code_in_question = parse_course_code_from_text(question.upper())
|
| 309 |
+
if code_in_question:
|
| 310 |
+
return code_in_question.upper()
|
| 311 |
+
|
| 312 |
+
q = question.lower()
|
| 313 |
+
|
| 314 |
+
# Match against titles in the FAQ.
|
| 315 |
+
for option in COURSE_OPTIONS:
|
| 316 |
+
if option == "All courses":
|
| 317 |
+
continue
|
| 318 |
+
code = parse_selected_course(option)
|
| 319 |
+
title = option.split("β", 1)[-1].strip().lower()
|
| 320 |
+
|
| 321 |
+
# Full title or distinctive keywords.
|
| 322 |
+
if title and title in q:
|
| 323 |
+
return code
|
| 324 |
+
|
| 325 |
+
aliases = {
|
| 326 |
+
"AIN7301": ["python", "programming"],
|
| 327 |
+
"AIN7303": ["machine learning", "deep learning", "ml/dl", "mldl", "neural network", "cnn"],
|
| 328 |
+
"AIN7304": ["responsible ai", "ethics", "legal", "societal risk", "ai ethics"],
|
| 329 |
+
"COM7301": ["professional practice", "professional conduct", "sustainability", "employability"],
|
| 330 |
+
"COM7302": ["research methodology", "research methods", "proposal", "literature review", "zotero"],
|
| 331 |
+
"COM7303": ["statistics", "hypothesis", "confidence interval", "regression", "ab testing", "a/b"],
|
| 332 |
+
"DAT7301": ["data visualization", "data visualisation", "power bi", "tableau", "dashboard", "dax"]
|
| 333 |
+
}
|
| 334 |
+
if code in aliases and any(alias in q for alias in aliases[code]):
|
| 335 |
+
return code
|
| 336 |
+
|
| 337 |
+
return "ALL"
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def filter_faq_indices(course_code: str) -> List[int]:
|
| 341 |
+
if faq_df.empty:
|
| 342 |
+
return []
|
| 343 |
+
|
| 344 |
+
if course_code == "ALL":
|
| 345 |
+
return list(range(len(faq_df)))
|
| 346 |
+
|
| 347 |
+
codes = faq_df["course_code"].astype(str).str.upper()
|
| 348 |
+
return faq_df.index[(codes == course_code.upper()) | (codes == "ALL")].tolist()
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def filter_doc_indices(course_code: str) -> List[int]:
|
| 352 |
+
if not document_chunks:
|
| 353 |
+
return []
|
| 354 |
+
if course_code == "ALL":
|
| 355 |
+
return list(range(len(document_chunks)))
|
| 356 |
+
return [
|
| 357 |
+
i for i, chunk in enumerate(document_chunks)
|
| 358 |
+
if chunk.get("course_code", "").upper() == course_code.upper()
|
| 359 |
+
]
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def similarity_search(
|
| 363 |
+
query: str,
|
| 364 |
+
embeddings: np.ndarray,
|
| 365 |
+
candidate_indices: List[int],
|
| 366 |
+
top_k: int = 3
|
| 367 |
+
) -> List[Tuple[int, float]]:
|
| 368 |
+
if embeddings.size == 0 or not candidate_indices:
|
| 369 |
+
return []
|
| 370 |
+
|
| 371 |
+
q_emb = embedding_model.encode([query], normalize_embeddings=True)[0]
|
| 372 |
+
candidate_matrix = embeddings[candidate_indices]
|
| 373 |
+
scores = np.dot(candidate_matrix, q_emb)
|
| 374 |
+
order = np.argsort(scores)[::-1][:top_k]
|
| 375 |
+
|
| 376 |
+
return [(candidate_indices[int(i)], float(scores[int(i)])) for i in order]
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
# ------------------------------------------------------------
|
| 380 |
+
# Answer construction
|
| 381 |
+
# ------------------------------------------------------------
|
| 382 |
+
def format_faq_answer(row: pd.Series, score: float, show_sources: bool) -> str:
|
| 383 |
+
answer = str(row["answer"]).strip()
|
| 384 |
+
|
| 385 |
+
footer = ""
|
| 386 |
+
if show_sources:
|
| 387 |
+
footer = (
|
| 388 |
+
"\n\n---\n"
|
| 389 |
+
f"**Source:** {row['source_file']} \n"
|
| 390 |
+
f"**Category:** {row['category']} \n"
|
| 391 |
+
f"**FAQ match score:** {score:.2f}"
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
return f"{answer}{footer}"
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def generate_answer_from_chunks(question: str, chunks_with_scores: List[Tuple[Dict, float]]) -> str:
|
| 398 |
+
context = "\n\n".join([
|
| 399 |
+
f"Source: {chunk['source_file']} | Course: {chunk['course_code']} β {chunk['course_title']}\n{chunk['text']}"
|
| 400 |
+
for chunk, _ in chunks_with_scores
|
| 401 |
+
])
|
| 402 |
+
|
| 403 |
+
if generator is None:
|
| 404 |
+
primary = chunks_with_scores[0][0]
|
| 405 |
+
return (
|
| 406 |
+
"Based on the uploaded teaching plan, the most relevant information I found is:\n\n"
|
| 407 |
+
f"{safe_excerpt(primary['text'], 1400)}"
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
prompt = f"""
|
| 411 |
+
You are an academic support chatbot for MAIAD01 students.
|
| 412 |
+
Answer the student's question using only the teaching plan context below.
|
| 413 |
+
Do not invent deadlines, attendance rules, grades, or policy exceptions.
|
| 414 |
+
If the answer is not in the context, say that it is not available in the uploaded teaching plan and advise the student to check the LMS or academic office.
|
| 415 |
+
|
| 416 |
+
Teaching plan context:
|
| 417 |
+
{context}
|
| 418 |
+
|
| 419 |
+
Student question:
|
| 420 |
+
{question}
|
| 421 |
+
|
| 422 |
+
Answer:
|
| 423 |
"""
|
| 424 |
+
try:
|
| 425 |
+
generated = generator(prompt)[0]["generated_text"].strip()
|
| 426 |
+
return generated
|
| 427 |
+
except Exception:
|
| 428 |
+
primary = chunks_with_scores[0][0]
|
| 429 |
+
return (
|
| 430 |
+
"Based on the uploaded teaching plan, the most relevant information I found is:\n\n"
|
| 431 |
+
f"{safe_excerpt(primary['text'], 1400)}"
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def format_doc_answer(question: str, matches: List[Tuple[int, float]], show_sources: bool) -> str:
|
| 436 |
+
chunks_with_scores = [(document_chunks[i], score) for i, score in matches]
|
| 437 |
+
answer = generate_answer_from_chunks(question, chunks_with_scores)
|
| 438 |
+
|
| 439 |
+
if show_sources:
|
| 440 |
+
sources = "\n".join([
|
| 441 |
+
f"- {chunk['course_code']} β {chunk['course_title']} | {chunk['source_file']} | relevance score: {score:.2f}"
|
| 442 |
+
for chunk, score in chunks_with_scores
|
| 443 |
+
])
|
| 444 |
+
answer += f"\n\n---\n**Teaching plan sources used:**\n{sources}"
|
| 445 |
+
|
| 446 |
+
return answer
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def should_escalate(question: str) -> bool:
|
| 450 |
+
q = question.lower()
|
| 451 |
+
escalation_terms = [
|
| 452 |
+
"approve my extension", "approve extension", "medical", "personal case",
|
| 453 |
+
"what grade will i get", "change my grade", "exempt me", "attendance exemption",
|
| 454 |
+
"can i skip", "can you submit for me"
|
| 455 |
+
]
|
| 456 |
+
return any(term in q for term in escalation_terms)
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def chat(message: str, history, course_selection: str, show_sources: bool) -> str:
|
| 460 |
+
if not message or not message.strip():
|
| 461 |
+
return "Please type your question."
|
| 462 |
+
|
| 463 |
+
if should_escalate(message):
|
| 464 |
+
return (
|
| 465 |
+
"I cannot approve extensions, exemptions, grades, attendance exceptions, or personal academic decisions. "
|
| 466 |
+
"Please contact the module faculty or the academic office."
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
course_code = infer_course_from_question(message, course_selection)
|
| 470 |
+
|
| 471 |
+
# 1) Search curated FAQ first.
|
| 472 |
+
faq_indices = filter_faq_indices(course_code)
|
| 473 |
+
faq_matches = similarity_search(message, faq_embeddings, faq_indices, top_k=3)
|
| 474 |
+
|
| 475 |
+
if faq_matches:
|
| 476 |
+
best_index, best_score = faq_matches[0]
|
| 477 |
+
if best_score >= FAQ_THRESHOLD:
|
| 478 |
+
return format_faq_answer(faq_df.loc[best_index], best_score, show_sources)
|
| 479 |
+
|
| 480 |
+
# 2) Search the source teaching plans if FAQ confidence is lower.
|
| 481 |
+
doc_indices = filter_doc_indices(course_code)
|
| 482 |
+
doc_matches = similarity_search(message, doc_embeddings, doc_indices, top_k=4)
|
| 483 |
+
|
| 484 |
+
if doc_matches:
|
| 485 |
+
best_doc_score = doc_matches[0][1]
|
| 486 |
+
if best_doc_score >= DOC_THRESHOLD:
|
| 487 |
+
return format_doc_answer(message, doc_matches, show_sources)
|
| 488 |
+
|
| 489 |
+
# 3) Low-confidence fallback.
|
| 490 |
+
course_note = "" if course_code == "ALL" else f" for {course_code}"
|
| 491 |
+
return (
|
| 492 |
+
f"I could not find a reliable answer in the uploaded teaching plans{course_note}. "
|
| 493 |
+
"Please check the LMS or contact the faculty/academic office. "
|
| 494 |
+
"Try asking with the course code, for example: 'What is the assessment structure for AIN7301?'"
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
# ------------------------------------------------------------
|
| 499 |
+
# Gradio UI
|
| 500 |
+
# ------------------------------------------------------------
|
| 501 |
+
examples = [
|
| 502 |
+
["Which courses are covered by this chatbot?", "All courses", True],
|
| 503 |
+
["What is the assessment structure for AIN7301?", "AIN7301 β Python Programming", True],
|
| 504 |
+
["What is covered in Week 3 for AIN7303?", "AIN7303 β Machine Learning and Deep Learning Techniques", True],
|
| 505 |
+
["What are the learning outcomes for AIN7304?", "AIN7304 β Responsible AI β Ethics, Legal & Societal Risks", True],
|
| 506 |
+
["What is the final project for DAT7301?", "DAT7301 β Data Analysis and Data Visualization", True],
|
| 507 |
+
["When is the deadline?", "All courses", True],
|
| 508 |
+
["Is attendance compulsory?", "All courses", True],
|
| 509 |
+
]
|
| 510 |
+
|
| 511 |
+
description = """
|
| 512 |
+
Ask questions based on the uploaded teaching plans. The assistant checks the curated FAQ first and then searches the full teaching plan documents.
|
| 513 |
+
For exact deadlines, attendance exceptions, grades, medical cases, or extension approvals, students must check the LMS or contact the academic office.
|
| 514 |
"""
|
| 515 |
+
|
| 516 |
+
demo = gr.ChatInterface(
|
| 517 |
+
fn=chat,
|
| 518 |
+
title=APP_TITLE,
|
| 519 |
+
description=description,
|
| 520 |
additional_inputs=[
|
| 521 |
+
gr.Dropdown(
|
| 522 |
+
choices=COURSE_OPTIONS,
|
| 523 |
+
value="All courses",
|
| 524 |
+
label="Course filter"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 525 |
),
|
| 526 |
+
gr.Checkbox(
|
| 527 |
+
value=True,
|
| 528 |
+
label="Show teaching-plan sources"
|
| 529 |
+
)
|
| 530 |
],
|
| 531 |
+
examples=examples
|
| 532 |
)
|
| 533 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 534 |
if __name__ == "__main__":
|
| 535 |
demo.launch()
|
faq.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
sentence-transformers
|
| 3 |
+
pandas
|
| 4 |
+
numpy
|
| 5 |
+
python-docx
|
| 6 |
+
pypdf
|
| 7 |
+
scikit-learn
|
| 8 |
+
transformers
|
| 9 |
+
torch
|
teaching_plan_chatbot_package.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ba3eb9709d5f1bb2781f78fe8b840d826a52264f0858d327ac8fbc788b8ef506
|
| 3 |
+
size 1303040
|