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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78bcefc
1701dd3
 
 
 
 
78bcefc
1701dd3
 
 
 
78bcefc
1701dd3
9f27cdc
1701dd3
 
78bcefc
1701dd3
78bcefc
 
 
 
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
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()