Wfafa commited on
Commit
a39fa98
ยท
verified ยท
1 Parent(s): adfc96d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +183 -122
app.py CHANGED
@@ -1,125 +1,186 @@
 
1
  import gradio as gr
2
- import time
3
-
4
- # ========================================
5
- # ๐Ÿ’ฌ AI Response Function (Replace this with your real AI)
6
- # ========================================
7
- def ai_response(message, history):
8
- # Example: Simulate AI typing delay
9
- time.sleep(0.8)
10
- # You can connect this to any API (e.g., DeepSeek, Hugging Face, OpenAI)
11
- return f"๐Ÿค– AI: I understood your question โ€” '{message}'. Letโ€™s explore that together!"
12
-
13
- # ========================================
14
- # โš™๏ธ Chat Logic
15
- # ========================================
16
- def respond(message, history):
17
- history = history or []
18
- bot_message = ai_response(message, history)
19
- history.append((message, bot_message))
20
- return "", history
21
-
22
-
23
- # ========================================
24
- # ๐ŸŽจ Gradio Interface
25
- # ========================================
26
- with gr.Blocks(css="""
27
- body {
28
- background: linear-gradient(135deg, #0d0d0d 0%, #1a1a1a 100%);
29
- color: #f0f0f0;
30
- font-family: 'Roboto', sans-serif;
31
- }
32
- #chatbot {
33
- background-color: transparent !important;
34
- border: none !important;
35
- }
36
- .send-btn {
37
- background: linear-gradient(135deg, #03dac6 0%, #00bfa5 100%) !important;
38
- color: #0d0d0d !important;
39
- border: none !important;
40
- font-weight: bold;
41
- border-radius: 25px !important;
42
- padding: 10px 20px !important;
43
- transition: 0.3s;
44
- }
45
- .send-btn:hover {
46
- transform: scale(1.05);
47
- box-shadow: 0 0 12px rgba(3, 218, 198, 0.6);
48
- }
49
- .sidebar {
50
- background-color: #2a2a2a;
51
- padding: 25px;
52
- border-right: 2px solid #444;
53
- box-shadow: inset -5px 0 10px rgba(0,0,0,0.4);
54
- height: 100vh;
55
- }
56
- .sidebar h2 {
57
- color: #03dac6;
58
- text-align: center;
59
- font-weight: 400;
60
- margin-bottom: 25px;
61
- }
62
- .sidebar-btn {
63
- display: block;
64
- width: 100%;
65
- background: transparent;
66
- color: #f0f0f0;
67
- border: none;
68
- text-align: left;
69
- padding: 12px 15px;
70
- border-radius: 8px;
71
- font-size: 15px;
72
- margin-bottom: 5px;
73
- cursor: pointer;
74
- transition: all 0.3s ease;
75
- }
76
- .sidebar-btn:hover {
77
- background-color: #444;
78
- transform: translateX(5px);
79
- }
80
- .footer {
81
- font-size: 12px;
82
- text-align: center;
83
- margin-top: auto;
84
- color: #aaa;
85
- }
86
- """) as demo:
87
-
88
- # ========== Layout ==========
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  with gr.Row():
90
- # Sidebar Section
91
- with gr.Column(scale=1, elem_classes="sidebar"):
92
- gr.HTML("<h2>AI Study Agent</h2>")
93
- tutor_btn = gr.Button("๐Ÿ“˜ Study Tutor", elem_classes="sidebar-btn")
94
- planner_btn = gr.Button("๐Ÿ—“๏ธ Study Planner", elem_classes="sidebar-btn")
95
- advisor_btn = gr.Button("๐Ÿง  Study Advisor", elem_classes="sidebar-btn")
96
- gr.Markdown("<hr>")
97
- gr.Markdown("โœจ <small>Designed by Cherry</small>", elem_classes="footer")
98
-
99
- # Main Chat Section
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  with gr.Column(scale=4):
101
- chatbot = gr.Chatbot(label="", elem_id="chatbot", height=550)
102
- with gr.Row():
103
- msg = gr.Textbox(placeholder="Type your question here...", show_label=False, scale=5)
104
- send = gr.Button("Send", elem_classes="send-btn", scale=1)
105
-
106
- # Chat connections
107
- msg.submit(respond, [msg, chatbot], [msg, chatbot])
108
- send.click(respond, [msg, chatbot], [msg, chatbot])
109
-
110
- # Sidebar button responses
111
- def sidebar_action(choice, history):
112
- response = f"โœจ You selected **{choice}** โ€” How can I assist with that?"
113
- history = history or []
114
- history.append((f"{choice}", response))
115
- return history
116
-
117
- tutor_btn.click(sidebar_action, ["Study Tutor", chatbot], chatbot)
118
- planner_btn.click(sidebar_action, ["Study Planner", chatbot], chatbot)
119
- advisor_btn.click(sidebar_action, ["Study Advisor", chatbot], chatbot)
120
-
121
-
122
- # ========================================
123
- # ๐Ÿš€ Launch App
124
- # ========================================
125
- demo.launch()
 
1
+ import os
2
  import gradio as gr
3
+ import requests
4
+ import json
5
+
6
+ # ๐ŸŒ Web search function
7
+ def search_web(query):
8
+ try:
9
+ url = "https://api.duckduckgo.com/"
10
+ params = {"q": query, "format": "json", "no_html": 1, "skip_disambig": 1}
11
+ response = requests.get(url, params=params)
12
+ data = response.json()
13
+
14
+ if data.get("AbstractText"):
15
+ return data["AbstractText"]
16
+ elif data.get("RelatedTopics"):
17
+ topics = [t.get("Text", "") for t in data["RelatedTopics"] if "Text" in t]
18
+ return " ".join(topics[:3])
19
+ else:
20
+ return "No useful information found."
21
+ except Exception as e:
22
+ return f"Search error: {e}"
23
+
24
+ # ๐Ÿง  Memory setup
25
+ HF_TOKEN = os.getenv("HF_TOKEN")
26
+ MEMORY_FILE = "memory.json"
27
+
28
+ def load_memory():
29
+ if os.path.exists(MEMORY_FILE):
30
+ with open(MEMORY_FILE, "r") as f:
31
+ return json.load(f)
32
+ return []
33
+
34
+ def save_memory(memory):
35
+ with open(MEMORY_FILE, "w") as f:
36
+ json.dump(memory, f)
37
+
38
+ memory = load_memory()
39
+
40
+ # ๐Ÿ’ฌ Chat function
41
+ def chat_with_model(message, history, context):
42
+ if not isinstance(history, list):
43
+ history = []
44
+
45
+ # ๐ŸŒ Web search mode
46
+ if message.lower().startswith("search "):
47
+ query = message[7:]
48
+ search_result = search_web(query)
49
+ history.append((message, f"๐Ÿ”Ž Here's what I found online:\n\n{search_result}"))
50
+ save_memory(history)
51
+ return history, history
52
+
53
+ # ๐Ÿง  Build conversation
54
+ conversation = [
55
+ {"role": "system", "content": (
56
+ "You are EduAI, a multilingual educational AI assistant created by a Sri Lankan student named Wafa Fazly. "
57
+ "When solving math, explain step-by-step like a professional tutor. "
58
+ "Use Markdown and LaTeX formatting for equations (use \\[ and \\]). "
59
+ "Keep answers neat, structured, and student-friendly."
60
+ )}
61
+ ]
62
+
63
+ for past_user, past_bot in history[-5:]:
64
+ conversation.append({"role": "user", "content": past_user})
65
+ conversation.append({"role": "assistant", "content": past_bot})
66
+
67
+ conversation.append({"role": "user", "content": message})
68
+
69
+ # ๐Ÿš€ Send to Hugging Face model
70
+ try:
71
+ response = requests.post(
72
+ "https://router.huggingface.co/v1/chat/completions",
73
+ headers={
74
+ "Authorization": f"Bearer {HF_TOKEN}",
75
+ "Content-Type": "application/json"
76
+ },
77
+ json={
78
+ "model": "deepseek-ai/DeepSeek-V3.2-Exp:novita",
79
+ "messages": conversation
80
+ }
81
+ )
82
+
83
+ data = response.json()
84
+ reply = data["choices"][0]["message"]["content"]
85
+
86
+ # ๐Ÿงฎ Clean up math formatting
87
+ reply = reply.replace("Step", "\n\n**Step")
88
+ reply = reply.replace(":", ":**")
89
+ reply = reply.replace("\\[", "\n\n\\[")
90
+ reply = reply.replace("\\]", "\\]\n\n")
91
+
92
+ if "\\" in reply or "log_" in reply or "^" in reply:
93
+ reply = f"{reply}"
94
+
95
+ history.append((message, reply))
96
+ save_memory(history)
97
+ return history, history
98
+
99
+ except Exception as e:
100
+ print("Error:", e)
101
+ history.append((message, "๐Ÿ˜… EduAI is having trouble connecting right now. Please try again later!"))
102
+ return history, history
103
+
104
+ # ๐Ÿ“˜ Sidebar context update
105
+ def update_context(choice):
106
+ if not choice:
107
+ return "๐Ÿ“˜ **You are in General Mode.** Ask EduAI anything about your studies!"
108
+ return f"๐Ÿ“˜ **You selected {choice} mode.** Ask anything related to this topic!"
109
+
110
+ # ๐Ÿงน Clear chat memory
111
+ def clear_memory():
112
+ if os.path.exists(MEMORY_FILE):
113
+ os.remove(MEMORY_FILE)
114
+ return [], "๐Ÿงน Chat memory cleared! Start fresh."
115
+
116
+ # ๐ŸŽจ Gradio Interface (UI Improved)
117
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="violet")) as iface:
118
+ gr.Markdown(
119
+ """
120
+ # ๐ŸŽ“ **EduAI โ€” Your Smart Study Companion**
121
+ Welcome to **EduAI**, your friendly study assistant! ๐Ÿ’ฌ
122
+ Get help in **Science, ICT, English, Mathematics**, and more.
123
+ """
124
+ )
125
+
126
  with gr.Row():
127
+ with gr.Column(scale=1, min_width=230):
128
+ gr.Markdown("### ๐Ÿงญ **Main Menu**")
129
+
130
+ with gr.Accordion("๐Ÿ“š Subject Tutor", open=False):
131
+ subj = gr.Radio(
132
+ ["Science ๐Ÿงช", "ICT ๐Ÿ’ป", "English ๐Ÿ“˜", "Mathematics โž—"],
133
+ label="Choose a subject"
134
+ )
135
+
136
+ with gr.Accordion("๐Ÿ—“ Study Planner", open=False):
137
+ planner = gr.Radio(
138
+ ["View Plan ๐Ÿ“…", "Add Task โœ๏ธ", "Study Tips ๐Ÿ’ก"],
139
+ label="Planner Options"
140
+ )
141
+
142
+ with gr.Accordion("๐ŸŒ Languages", open=False):
143
+ lang = gr.Radio(
144
+ ["Learn Sinhala ๐Ÿ‡ฑ๐Ÿ‡ฐ", "Learn Tamil ๐Ÿ‡ฎ๐Ÿ‡ณ", "Learn English ๐Ÿ‡ฌ๐Ÿ‡ง", "Learn Spanish ๐Ÿ‡ช๐Ÿ‡ธ"],
145
+ label="Language Options"
146
+ )
147
+
148
+ with gr.Accordion("โš™๏ธ Settings", open=False):
149
+ clear_btn = gr.Button("๐Ÿงน Clear Memory")
150
+
151
+ with gr.Accordion("๐Ÿ‘ฉโ€๐ŸŽ“ About", open=False):
152
+ gr.Markdown(
153
+ """
154
+ EduAI was designed and fine-tuned by **Wafa Fazly**,
155
+ a passionate Sri Lankan student ๐Ÿ‘ฉโ€๐Ÿ’ป
156
+ to help learners explore **Science, ICT, English, and more** โ€”
157
+ in a smart and friendly way! ๐ŸŒŸ
158
+ """
159
+ )
160
+
161
  with gr.Column(scale=4):
162
+ context_display = gr.Markdown("๐Ÿ“˜ **You are in General Mode.** Ask EduAI anything about your studies!")
163
+ chatbot = gr.Chatbot(
164
+ label="๐Ÿ’ฌ EduAI Chat Window",
165
+ height=450,
166
+ render_markdown=True,
167
+ bubble_full_width=False,
168
+ latex_delimiters=[
169
+ {"left": "$$", "right": "$$", "display": True},
170
+ {"left": "\\[", "right": "\\]", "display": True}
171
+ ]
172
+ )
173
+ msg = gr.Textbox(
174
+ label="๐Ÿ’ญ Type your question here...",
175
+ placeholder="Ask EduAI anything about your studies..."
176
+ )
177
+ send = gr.Button("โœจ Send Message")
178
+
179
+ # ๐Ÿช„ Event handlers
180
+ subj.change(update_context, inputs=subj, outputs=context_display)
181
+ planner.change(update_context, inputs=planner, outputs=context_display)
182
+ lang.change(update_context, inputs=lang, outputs=context_display)
183
+ send.click(chat_with_model, inputs=[msg, chatbot, context_display], outputs=[chatbot, chatbot])
184
+ clear_btn.click(clear_memory, outputs=[chatbot, context_display])
185
+
186
+ iface.launch()