File size: 3,272 Bytes
a755767
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import pdfplumber
import spaces

# Load and extract text from your course documents
def load_documents():
    files = ["AIN7304_Responsible AI_TP_28Nov2025.pdf"]
    text = ""
    for f in files:
        try:
            with pdfplumber.open(f) as pdf:
                for page in pdf.pages:
                    text += page.extract_text() or ""
        except Exception as e:
            print(f"Could not load {f}: {e}")
    return text

course_text = load_documents()

@spaces.GPU
def answer(question):
    if not question.strip():
        return "Please type a question."

    question_lower = question.lower()
    question_words = set(question_lower.split())
    
    # Remove common stop words so only meaningful words drive matching
    stop_words = {"what", "is", "the", "are", "a", "an", "do", "does", "i",
                  "my", "how", "when", "where", "can", "will", "if", "of",
                  "to", "for", "in", "and", "or", "it", "be", "have", "has"}
    keywords = question_words - stop_words

    # Split text into Q&A blocks (each block = one Q: ... A: ... pair)
    import re
    blocks = re.split(r'(?=Q:)', course_text)
    blocks = [b.strip() for b in blocks if b.strip() and 'A:' in b]

    # Score each block by how many keywords appear in the Q line only
    scored = []
    for block in blocks:
        lines = block.split('\n')
        q_line = lines[0].lower() if lines else ""
        # Score = keywords matched in the question line
        score = sum(1 for kw in keywords if kw in q_line)
        if score > 0:
            scored.append((score, block))

    scored.sort(reverse=True)

    if not scored:
        # Fallback: search full text for keyword-dense sentences
        sentences = [s.strip() for s in course_text.replace("\n", ". ").split(".") if len(s.strip()) > 30]
        sentence_scores = []
        for s in sentences:
            score = sum(1 for kw in keywords if kw in s.lower())
            if score > 0:
                sentence_scores.append((score, s))
        sentence_scores.sort(reverse=True)
        top = [s for _, s in sentence_scores[:2]]
        if top:
            return "\n\n".join(top)
        return "I could not find an answer in the course documents. Please contact Dr. Anitha directly."

    # Return the best matching Q&A block, cleanly formatted
    best = scored[0][1]
    
    # Clean up the block for display
    best = best.replace("Q:", "").strip()
    if "A:" in best:
        parts = best.split("A:", 1)
        question_part = parts[0].strip()
        answer_part = parts[1].strip()
        return f"📌 {question_part}\n\n{answer_part}"
    
    return best

demo = gr.Interface(
    fn=answer,
    inputs=gr.Textbox(placeholder="Ask a question about the course...", label="Your Question"),
    outputs=gr.Textbox(label="Answer from Course Documents"),
    title="Dr. Anitha's Course Assistant",
    description="Ask me anything about Responsible AI. I only answer from official course documents.",
    examples=[
        ["What is the late submission policy?"],
        ["How much is the final project worth?"],
        ["Can I resubmit an assignment?"],
        ["What tools do I need for this course?"],
        ["Is attendance compulsory?"],
    ]
)

demo.launch()