File size: 5,911 Bytes
030f984
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Study Ocean AI Mentor β€” Gradio Web Interface

A beautiful, student-friendly chat interface for the RAG-based
doubt-solving mentor. Built with Gradio for easy deployment.
"""

import gradio as gr
from rag_chain import get_chain, ask_question

# ─── Custom CSS for Premium Look ────────────────────────────
CUSTOM_CSS = """
/* Global */
.gradio-container {
    max-width: 900px !important;
    margin: auto !important;
    font-family: 'Inter', 'Segoe UI', sans-serif !important;
}

/* Header */
.header-section {
    text-align: center;
    padding: 20px 0 10px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 16px;
    margin-bottom: 20px;
    color: white;
}

.header-section h1 {
    font-size: 2em;
    margin: 0;
    color: white !important;
}

.header-section p {
    opacity: 0.9;
    margin: 5px 0 0;
    font-size: 1.05em;
    color: #e8e8ff !important;
}

/* Chat area */
.chatbot {
    border-radius: 12px !important;
    border: 1px solid #e2e8f0 !important;
    min-height: 450px !important;
}

/* Source cards */
.source-card {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 10px 14px;
    margin: 4px 0;
    font-size: 0.9em;
}

.source-card strong {
    color: #6366f1;
}

/* Override dark mode */
.dark .source-card {
    background: #1e293b;
    border-color: #334155;
}

/* Buttons */
.primary-btn {
    background: linear-gradient(135deg, #667eea, #764ba2) !important;
    border: none !important;
    color: white !important;
    border-radius: 10px !important;
    font-weight: 600 !important;
    padding: 10px 24px !important;
}

.primary-btn:hover {
    opacity: 0.9 !important;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4) !important;
}
"""

# ─── Initialize chain on startup ────────────────────────────
print("πŸ”„ Initializing Study Ocean AI Mentor...")
chain = get_chain()
print("βœ… Ready to answer student doubts!\n")


def format_sources(sources: list) -> str:
    """Format source documents into a readable string."""
    if not sources:
        return ""
    
    lines = ["\n\n---\nπŸ“– **Sources Referenced:**\n"]
    for i, src in enumerate(sources, 1):
        lines.append(f"**{i}.** `{src['subject']}` β†’ _{src['file']}_")
    return "\n".join(lines)


def respond(message: str, chat_history: list) -> tuple:
    """Handle a student's question and return the mentor's response."""
    if not message.strip():
        return "", chat_history

    # Get answer from RAG chain
    result = ask_question(chain, message)
    answer = result["answer"]
    sources = result["sources"]

    # Append source references to the answer
    answer_with_sources = answer + format_sources(sources)

    # Update chat history
    chat_history.append((message, answer_with_sources))
    
    return "", chat_history


def clear_chat():
    """Clear the chat history."""
    return [], ""


# ─── Build Gradio Interface ─────────────────────────────────
with gr.Blocks(title="Study Ocean AI Mentor") as app:
    
    # Header
    gr.HTML("""
    <div class="header-section">
        <h1>πŸŽ“ Study Ocean AI Mentor</h1>
        <p>Ask any doubt from your study material β€” I'll explain it step by step!</p>
    </div>
    """)

    # Chatbot
    chatbot = gr.Chatbot(
        label="πŸ’¬ Chat with Your Mentor",
        elem_classes=["chatbot"],
        height=480,
        avatar_images=(None, "https://api.dicebear.com/7.x/bottts/svg?seed=mentor&backgroundColor=6366f1"),
    )

    # Input area
    with gr.Row():
        msg = gr.Textbox(
            placeholder="Type your doubt here... e.g., 'Explain Newton's third law with examples'",
            label="Your Question",
            scale=5,
            lines=1,
            max_lines=3,
            show_label=False,
            container=False,
        )
        submit_btn = gr.Button("Ask πŸš€", elem_classes=["primary-btn"], scale=1)

    # Action buttons
    with gr.Row():
        clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", size="sm")

    # Example questions
    gr.Examples(
        examples=[
            "What are Newton's laws of motion? Explain with examples.",
            "Explain the difference between mitosis and meiosis.",
            "What is the Pythagorean theorem and how do I use it?",
            "Explain the concept of supply and demand in economics.",
            "What are the key features of the Indian Constitution?",
            "Solve: Find the derivative of f(x) = 3xΒ² + 2x - 5",
        ],
        inputs=msg,
        label="πŸ’‘ Try these example questions:",
    )

    # Tips section
    with gr.Accordion("πŸ“Œ Tips for Better Answers", open=False):
        gr.Markdown("""
        - **Be specific**: Instead of "explain physics", ask "explain projectile motion with examples"
        - **Mention the topic**: "In organic chemistry, what is an SN2 reaction?"  
        - **Ask for steps**: "Solve step by step: integrate sin(x)cos(x) dx"
        - **Request comparisons**: "Compare TCP and UDP protocols"
        - **Ask for formulas**: "List all the trigonometric identities"
        """)

    # Event handlers
    msg.submit(respond, [msg, chatbot], [msg, chatbot])
    submit_btn.click(respond, [msg, chatbot], [msg, chatbot])
    clear_btn.click(clear_chat, outputs=[chatbot, msg])


# ─── Launch ─────────────────────────────────────────────────
if __name__ == "__main__":
    app.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_error=True,
        css=CUSTOM_CSS,
        theme=gr.themes.Soft(),
    )