import os import re from pathlib import Path from typing import List, Dict, Tuple import gradio as gr import numpy as np import pandas as pd from sentence_transformers import SentenceTransformer # Optional document readers from docx import Document from pypdf import PdfReader # ------------------------------------------------------------ # Configuration # ------------------------------------------------------------ APP_TITLE = "MAIAD01 Teaching Plan Chatbot" FAQ_FILE = "faq.csv" TEACHING_PLAN_DIR = "." EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2" # FAQ answers are preferred because they are curated from the teaching plans. FAQ_THRESHOLD = float(os.getenv("FAQ_THRESHOLD", "0.48")) DOC_THRESHOLD = float(os.getenv("DOC_THRESHOLD", "0.24")) CHUNK_WORDS = int(os.getenv("CHUNK_WORDS", "260")) CHUNK_OVERLAP = int(os.getenv("CHUNK_OVERLAP", "45")) # Generation is optional. For a faster and safer academic demo, keep this false. # Set USE_GENERATOR=true in Hugging Face Space secrets/environment variables # if you want Flan-T5 to summarise retrieved chunks. USE_GENERATOR = os.getenv("USE_GENERATOR", "false").lower() == "true" GENERATOR_MODEL = os.getenv("GENERATOR_MODEL", "google/flan-t5-small") # ------------------------------------------------------------ # Utility functions # ------------------------------------------------------------ def clean_text(text: str) -> str: """Normalise whitespace without changing academic content.""" if text is None: return "" return re.sub(r"\s+", " ", str(text).replace("\xa0", " ")).strip() def safe_excerpt(text: str, max_chars: int = 1400) -> str: text = clean_text(text) if len(text) <= max_chars: return text return text[:max_chars].rsplit(" ", 1)[0] + "..." def parse_course_code_from_text(text: str) -> str: match = re.search(r"\b[A-Z]{3}\d{4}\b", text or "") return match.group(0) if match else "" def read_docx(path: Path) -> str: """Read paragraphs and tables from a DOCX teaching plan.""" doc = Document(str(path)) parts = [] for paragraph in doc.paragraphs: text = clean_text(paragraph.text) if text: parts.append(text) for table_index, table in enumerate(doc.tables, start=1): parts.append(f"[Table {table_index}]") for row in table.rows: cells = [clean_text(cell.text) for cell in row.cells] if any(cells): parts.append(" | ".join(cells)) return "\n".join(parts) def read_pdf(path: Path) -> str: """Read text-based PDF files. Scanned PDFs may require OCR, which is not included here.""" reader = PdfReader(str(path)) pages = [] for page_number, page in enumerate(reader.pages, start=1): page_text = page.extract_text() or "" if page_text.strip(): pages.append(f"[Page {page_number}] {page_text}") return "\n".join(pages) def read_txt(path: Path) -> str: return path.read_text(encoding="utf-8", errors="ignore") def read_supported_file(path: Path) -> str: suffix = path.suffix.lower() if suffix == ".docx": return read_docx(path) if suffix == ".pdf": return read_pdf(path) if suffix in [".txt", ".md", ".csv"]: return read_txt(path) return "" def infer_course_title_from_faq(faq_df: pd.DataFrame, course_code: str) -> str: if not course_code or faq_df.empty: return "" rows = faq_df[faq_df["course_code"].astype(str).str.upper() == course_code.upper()] if not rows.empty: return str(rows.iloc[0].get("course_title", "")).strip() return "" def chunk_text(text: str, source_file: str, course_code: str, course_title: str) -> List[Dict]: """Split a document into overlapping chunks for semantic search.""" words = clean_text(text).split() chunks = [] start = 0 chunk_id = 1 while start < len(words): end = start + CHUNK_WORDS chunk = " ".join(words[start:end]) if len(chunk) > 120: chunks.append({ "chunk_id": f"{course_code or 'DOC'}-{chunk_id:04d}", "course_code": course_code, "course_title": course_title, "source_file": source_file, "text": chunk }) chunk_id += 1 if end >= len(words): break start = max(0, end - CHUNK_OVERLAP) return chunks # ------------------------------------------------------------ # Load FAQ # ------------------------------------------------------------ def load_faq() -> pd.DataFrame: path = Path(FAQ_FILE) if not path.exists(): columns = [ "id", "course_code", "course_title", "category", "student_question", "alternate_questions", "answer", "source_file", "tags", "priority" ] return pd.DataFrame(columns=columns) df = pd.read_csv(path).fillna("") required = [ "id", "course_code", "course_title", "category", "student_question", "alternate_questions", "answer", "source_file", "tags", "priority" ] for col in required: if col not in df.columns: df[col] = "" return df[required] faq_df = load_faq() # ------------------------------------------------------------ # Load teaching plan documents # ------------------------------------------------------------ def load_teaching_plan_chunks() -> List[Dict]: plan_dir = Path(TEACHING_PLAN_DIR) if not plan_dir.exists(): return [] all_chunks = [] supported = [".docx", ".pdf", ".txt", ".md", ".csv"] for path in sorted(plan_dir.iterdir()): if not path.is_file() or path.suffix.lower() not in supported: continue text = read_supported_file(path) if not text.strip(): continue course_code = parse_course_code_from_text(path.name) or parse_course_code_from_text(text) course_title = infer_course_title_from_faq(faq_df, course_code) # Fallback title extraction for files not represented in FAQ if not course_title: title_match = re.search(r"Course Title:\s*\|?\s*([^\n|]+)", text, re.I) course_title = clean_text(title_match.group(1)) if title_match else path.stem all_chunks.extend(chunk_text(text, path.name, course_code, course_title)) return all_chunks document_chunks = load_teaching_plan_chunks() # ------------------------------------------------------------ # Build semantic indexes # ------------------------------------------------------------ print("Loading embedding model...") embedding_model = SentenceTransformer(EMBEDDING_MODEL) def build_faq_search_texts(df: pd.DataFrame) -> List[str]: texts = [] for _, row in df.iterrows(): texts.append( " ".join([ str(row["course_code"]), str(row["course_title"]), str(row["category"]), str(row["student_question"]), str(row["alternate_questions"]), str(row["tags"]), safe_excerpt(str(row["answer"]), 450) ]) ) return texts faq_search_texts = build_faq_search_texts(faq_df) if faq_search_texts: faq_embeddings = embedding_model.encode(faq_search_texts, normalize_embeddings=True) else: faq_embeddings = np.empty((0, 384)) doc_search_texts = [ " ".join([ chunk["course_code"], chunk["course_title"], chunk["source_file"], chunk["text"] ]) for chunk in document_chunks ] if doc_search_texts: doc_embeddings = embedding_model.encode(doc_search_texts, normalize_embeddings=True) else: doc_embeddings = np.empty((0, 384)) # Optional generator generator = None if USE_GENERATOR: try: from transformers import pipeline print(f"Loading generator model: {GENERATOR_MODEL}") generator = pipeline( "text2text-generation", model=GENERATOR_MODEL, max_new_tokens=220 ) except Exception as exc: print(f"Generator could not be loaded. Falling back to retrieval-only mode. Error: {exc}") generator = None # ------------------------------------------------------------ # Course options and filtering # ------------------------------------------------------------ def get_course_options() -> List[str]: course_pairs = [] if not faq_df.empty: for _, row in faq_df.iterrows(): code = str(row["course_code"]).strip() title = str(row["course_title"]).strip() if code and code.upper() != "ALL" and title: course_pairs.append((code, title)) for chunk in document_chunks: code = chunk.get("course_code", "").strip() title = chunk.get("course_title", "").strip() if code and title: course_pairs.append((code, title)) unique = [] seen = set() for code, title in course_pairs: key = code.upper() if key not in seen: seen.add(key) unique.append(f"{code} – {title}") return ["All courses"] + unique COURSE_OPTIONS = get_course_options() def parse_selected_course(course_selection: str) -> str: if not course_selection or course_selection == "All courses": return "ALL" match = re.match(r"([A-Z]{3}\d{4})", course_selection.strip()) return match.group(1).upper() if match else "ALL" def infer_course_from_question(question: str, selected_course: str) -> str: selected_code = parse_selected_course(selected_course) if selected_code != "ALL": return selected_code # Course code in the question takes priority. code_in_question = parse_course_code_from_text(question.upper()) if code_in_question: return code_in_question.upper() q = question.lower() # Match against titles in the FAQ. for option in COURSE_OPTIONS: if option == "All courses": continue code = parse_selected_course(option) title = option.split("–", 1)[-1].strip().lower() # Full title or distinctive keywords. if title and title in q: return code aliases = { "AIN7301": ["python", "programming"], "AIN7303": ["machine learning", "deep learning", "ml/dl", "mldl", "neural network", "cnn"], "AIN7304": ["responsible ai", "ethics", "legal", "societal risk", "ai ethics"], "COM7301": ["professional practice", "professional conduct", "sustainability", "employability"], "COM7302": ["research methodology", "research methods", "proposal", "literature review", "zotero"], "COM7303": ["statistics", "hypothesis", "confidence interval", "regression", "ab testing", "a/b"], "DAT7301": ["data visualization", "data visualisation", "power bi", "tableau", "dashboard", "dax"] } if code in aliases and any(alias in q for alias in aliases[code]): return code return "ALL" def filter_faq_indices(course_code: str) -> List[int]: if faq_df.empty: return [] if course_code == "ALL": return list(range(len(faq_df))) codes = faq_df["course_code"].astype(str).str.upper() return faq_df.index[(codes == course_code.upper()) | (codes == "ALL")].tolist() def filter_doc_indices(course_code: str) -> List[int]: if not document_chunks: return [] if course_code == "ALL": return list(range(len(document_chunks))) return [ i for i, chunk in enumerate(document_chunks) if chunk.get("course_code", "").upper() == course_code.upper() ] def similarity_search( query: str, embeddings: np.ndarray, candidate_indices: List[int], top_k: int = 3 ) -> List[Tuple[int, float]]: if embeddings.size == 0 or not candidate_indices: return [] q_emb = embedding_model.encode([query], normalize_embeddings=True)[0] candidate_matrix = embeddings[candidate_indices] scores = np.dot(candidate_matrix, q_emb) order = np.argsort(scores)[::-1][:top_k] return [(candidate_indices[int(i)], float(scores[int(i)])) for i in order] # ------------------------------------------------------------ # Answer construction # ------------------------------------------------------------ def format_faq_answer(row: pd.Series, score: float, show_sources: bool) -> str: answer = str(row["answer"]).strip() if show_sources: footer = ( "\n\n---\n" f"**Source:** {row['source_file']} \n" f"**Category:** {row['category']}" ) return f"{answer}{footer}" return answer def generate_answer_from_chunks(question: str, chunks_with_scores: List[Tuple[Dict, float]]) -> str: context = "\n\n".join([ f"Source: {chunk['source_file']} | Course: {chunk['course_code']} – {chunk['course_title']}\n{chunk['text']}" for chunk, _ in chunks_with_scores ]) if generator is None: primary = chunks_with_scores[0][0] return ( "Based on the uploaded teaching plan, the most relevant information I found is:\n\n" f"{safe_excerpt(primary['text'], 1400)}" ) prompt = f""" You are an academic support chatbot for MAIAD01 students. Answer the student's question using only the teaching plan context below. Do not invent deadlines, attendance rules, grades, or policy exceptions. 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. Teaching plan context: {context} Student question: {question} Answer: """ try: generated = generator(prompt)[0]["generated_text"].strip() return generated except Exception: primary = chunks_with_scores[0][0] return ( "Based on the uploaded teaching plan, the most relevant information I found is:\n\n" f"{safe_excerpt(primary['text'], 1400)}" ) def format_doc_answer(question: str, matches: List[Tuple[int, float]], show_sources: bool) -> str: chunks_with_scores = [(document_chunks[i], score) for i, score in matches] answer = generate_answer_from_chunks(question, chunks_with_scores) if show_sources: sources = "\n".join([ f"- {chunk['course_code']} – {chunk['course_title']} | {chunk['source_file']} | relevance score: {score:.2f}" for chunk, score in chunks_with_scores ]) answer += f"\n\n---\n**Teaching plan sources used:**\n{sources}" return answer def should_escalate(question: str) -> bool: q = question.lower() escalation_terms = [ "approve my extension", "approve extension", "medical", "personal case", "what grade will i get", "change my grade", "exempt me", "attendance exemption", "can i skip", "can you submit for me" ] return any(term in q for term in escalation_terms) def chat(message: str, history, course_selection: str, show_sources: bool) -> str: if not message or not message.strip(): return "Please type your question." if should_escalate(message): return ( "I cannot approve extensions, exemptions, grades, attendance exceptions, or personal academic decisions. " "Please contact the module faculty or the academic office." ) course_code = infer_course_from_question(message, course_selection) # 1) Search curated FAQ first. faq_indices = filter_faq_indices(course_code) faq_matches = similarity_search(message, faq_embeddings, faq_indices, top_k=3) if faq_matches: best_index, best_score = faq_matches[0] if best_score >= FAQ_THRESHOLD: return format_faq_answer(faq_df.loc[best_index], best_score, show_sources) # 2) Search the source teaching plans if FAQ confidence is lower. doc_indices = filter_doc_indices(course_code) doc_matches = similarity_search(message, doc_embeddings, doc_indices, top_k=4) if doc_matches: best_doc_score = doc_matches[0][1] if best_doc_score >= DOC_THRESHOLD: return format_doc_answer(message, doc_matches, show_sources) # 3) Low-confidence fallback. course_note = "" if course_code == "ALL" else f" for {course_code}" return ( f"I could not find a reliable answer in the uploaded teaching plans{course_note}. " "Please check the LMS or contact the faculty/academic office. " "Try asking with the course code, for example: 'What is the assessment structure for AIN7301?'" ) # ------------------------------------------------------------ # Gradio UI # ------------------------------------------------------------ examples = [ ["Which courses are covered by this chatbot?", "All courses", True], ["What is the assessment structure for AIN7301?", "AIN7301 – Python Programming", True], ["What is covered in Week 3 for AIN7303?", "AIN7303 – Machine Learning and Deep Learning Techniques", True], ["What are the learning outcomes for AIN7304?", "AIN7304 – Responsible AI – Ethics, Legal & Societal Risks", True], ["What is the final project for DAT7301?", "DAT7301 – Data Analysis and Data Visualization", True], ["When is the deadline?", "All courses", True], ["Is attendance compulsory?", "All courses", True], ] description = """ Ask questions based on the uploaded teaching plans. The assistant checks the curated FAQ first and then searches the full teaching plan documents. For exact deadlines, attendance exceptions, grades, medical cases, or extension approvals, students must check the LMS or contact the academic office. """ demo = gr.ChatInterface( fn=chat, title=APP_TITLE, description=description, additional_inputs=[ gr.Dropdown( choices=COURSE_OPTIONS, value="All courses", label="Course filter" ), gr.Checkbox( value=False, label="Show teaching-plan sources" ) ], examples=examples ) if __name__ == "__main__": demo.launch()