Wfafa commited on
Commit
ed034ae
·
verified ·
1 Parent(s): a4b1df1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -234
app.py CHANGED
@@ -1,240 +1,136 @@
1
- import os
2
  import gradio as gr
3
- import requests
4
- import json
5
-
6
- # 🌍 Web search
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
- if data.get("AbstractText"):
14
- return data["AbstractText"]
15
- elif data.get("RelatedTopics"):
16
- topics = [t.get("Text", "") for t in data["RelatedTopics"] if "Text" in t]
17
- return " ".join(topics[:3])
18
- else:
19
- return "No useful information found."
20
- except Exception as e:
21
- return f"Search error: {e}"
22
-
23
- # 🧠 Memory setup
24
- HF_TOKEN = os.getenv("HF_TOKEN")
25
- MEMORY_FILE = "memory.json"
26
-
27
- def load_memory():
28
- if os.path.exists(MEMORY_FILE):
29
- with open(MEMORY_FILE, "r") as f:
30
- return json.load(f)
31
- return []
32
-
33
- def save_memory(memory):
34
- with open(MEMORY_FILE, "w") as f:
35
- json.dump(memory, f)
36
-
37
- memory = load_memory()
38
-
39
- # 💬 Chat with AI
40
- def chat_with_model(message, history, context):
41
- if not isinstance(history, list):
42
- history = []
43
-
44
- if message.lower().startswith("search "):
45
- query = message[7:]
46
- result = search_web(query)
47
- history.append((message, f"🔎 Here's what I found online:\n\n{result}"))
48
- save_memory(history)
49
- return history, history
50
-
51
- conversation = [
52
- {"role": "system", "content": (
53
- "You are EduAI, a multilingual educational assistant created by a Sri Lankan student named Wafa Fazly. "
54
- "Explain step-by-step like a teacher. Use Markdown and LaTeX for math. "
55
- "Be friendly, clear, and structured."
56
- )}
57
- ]
58
-
59
- for u, b in history[-5:]:
60
- conversation.append({"role": "user", "content": u})
61
- conversation.append({"role": "assistant", "content": b})
62
-
63
- conversation.append({"role": "user", "content": message})
64
-
65
- try:
66
- response = requests.post(
67
- "https://router.huggingface.co/v1/chat/completions",
68
- headers={
69
- "Authorization": f"Bearer {HF_TOKEN}",
70
- "Content-Type": "application/json"
71
- },
72
- json={
73
- "model": "deepseek-ai/DeepSeek-V3.2-Exp:novita",
74
- "messages": conversation
75
- }
76
- )
77
- data = response.json()
78
- reply = data["choices"][0]["message"]["content"]
79
-
80
- reply = reply.replace("Step", "\n\n**Step")
81
- reply = reply.replace(":", ":**")
82
- reply = reply.replace("\\[", "\n\n\\[")
83
- reply = reply.replace("\\]", "\\]\n\n")
84
-
85
- history.append((message, reply))
86
- save_memory(history)
87
- return history, history
88
-
89
- except Exception as e:
90
- history.append((message, "😅 EduAI is having trouble connecting. Try again later!"))
91
- return history, history
92
-
93
- # 📘 Context update
94
- def update_context(choice):
95
- if not choice:
96
- return "📘 **You are in General Mode.** Ask EduAI anything!"
97
- return f"📘 **You selected {choice} mode.**"
98
-
99
- # 🧹 Clear memory
100
- def clear_memory():
101
- if os.path.exists(MEMORY_FILE):
102
- os.remove(MEMORY_FILE)
103
- return [], "🧹 Memory cleared! Start fresh."
104
-
105
- # 🎨 Dark theme CSS
106
- custom_css = """
107
- body {
108
- background-color: #0f0f12;
109
- color: #f0f0f0;
110
- font-family: 'Inter', sans-serif;
111
- margin: 0;
112
- height: 100vh;
113
- overflow: hidden;
114
- }
115
-
116
- .gradio-container {
117
- background-color: #0f0f12 !important;
118
- }
119
-
120
- #eduai-layout {
121
- display: flex;
122
- flex-direction: row;
123
- height: 100vh;
124
- overflow: hidden;
125
- }
126
-
127
- /* Sidebar */
128
- .sidebar {
129
- background-color: #18181c;
130
- color: #e0e0e0;
131
- width: 270px;
132
- padding: 18px;
133
- display: flex;
134
- flex-direction: column;
135
- border-right: 1px solid #2c2c2f;
136
- }
137
-
138
- /* Chat Area */
139
- .chat-area {
140
- background-color: #111113;
141
- flex-grow: 1;
142
- display: flex;
143
- flex-direction: column;
144
- justify-content: space-between;
145
- padding: 10px 20px 20px 20px;
146
- }
147
-
148
- .chat-header {
149
- text-align: center;
150
- font-size: 1.6em;
151
- font-weight: 700;
152
- color: #a78bfa;
153
- padding: 15px;
154
- border-bottom: 1px solid #2c2c2f;
155
- }
156
-
157
- textarea, input {
158
- background-color: #1e1e22 !important;
159
- color: #f0f0f0 !important;
160
- border-radius: 10px !important;
161
- border: 1px solid #3a3a3d !important;
162
- }
163
-
164
- button {
165
- background: linear-gradient(135deg, #7c3aed, #9333ea) !important;
166
- color: white !important;
167
- border-radius: 10px !important;
168
- border: none !important;
169
- transition: 0.2s ease-in-out;
170
- }
171
-
172
- button:hover {
173
- transform: scale(1.05);
174
- filter: brightness(1.2);
175
- }
176
-
177
- /* Chatbot bubble style */
178
- .chatbot > div {
179
- background-color: #1a1a1d !important;
180
- border-radius: 12px;
181
- }
182
- """
183
-
184
- # 🚀 Interface
185
- with gr.Blocks(css=custom_css) as iface:
186
- with gr.Row(elem_id="eduai-layout"):
187
- with gr.Column(elem_classes=["sidebar"]):
188
- gr.Markdown("## 🎓 EduAI")
189
- gr.Markdown("### 🧭 Main Menu")
190
-
191
- with gr.Accordion("📚 Subject Tutor", open=False):
192
- subj = gr.Radio(
193
- ["Science 🧪", "ICT 💻", "English 📘", "Mathematics ➗"],
194
- label="Choose a subject"
195
- )
196
-
197
- with gr.Accordion("🗓 Study Planner", open=False):
198
- planner = gr.Radio(
199
- ["View Plan 📅", "Add Task ✏️", "Study Tips 💡"],
200
- label="Planner Options"
201
- )
202
-
203
- with gr.Accordion("🌐 Languages", open=False):
204
- lang = gr.Radio(
205
- ["Learn Sinhala 🇱🇰", "Learn Tamil 🇮🇳", "Learn English 🇬🇧", "Learn Spanish 🇪🇸"],
206
- label="Language Options"
207
- )
208
-
209
  gr.Markdown("---")
210
- clear_btn = gr.Button("🧹 Clear Memory")
211
 
212
- gr.Markdown(
213
- "👩‍🎓 **About EduAI** \n"
214
- "Developed by **Wafa Fazly**, a passionate Sri Lankan student 🇱🇰 \n"
215
- "EduAI helps students explore **Science, ICT, English**, and more 🌟"
216
- )
217
 
218
- with gr.Column(elem_classes=["chat-area"]):
219
- gr.Markdown("<div class='chat-header'>💬 EduAI Smart Study Assistant</div>")
220
- context_display = gr.Markdown("📘 **You are in General Mode.** Ask EduAI anything!")
221
- chatbot = gr.Chatbot(
222
- label="",
223
- height=460,
224
- render_markdown=True,
225
- bubble_full_width=False
226
- )
227
- msg = gr.Textbox(
228
- placeholder="💭 Type your question here...",
229
- show_label=False
230
- )
231
- send = gr.Button("✨ Send Message")
232
 
233
- # ⚙️ Events
234
- subj.change(update_context, inputs=subj, outputs=context_display)
235
- planner.change(update_context, inputs=planner, outputs=context_display)
236
- lang.change(update_context, inputs=lang, outputs=context_display)
237
- send.click(chat_with_model, inputs=[msg, chatbot, context_display], outputs=[chatbot, chatbot])
238
- clear_btn.click(clear_memory, outputs=[chatbot, context_display])
239
 
240
- iface.launch()
 
 
1
  import gradio as gr
2
+ import time
3
+
4
+ # ========================================
5
+ # 💬 Your AI function (replace with your logic)
6
+ # ========================================
7
+ def ai_response(message, history):
8
+ # Here you can call your real AI model or API (e.g., DeepSeek or Hugging Face)
9
+ time.sleep(1) # simulate a delay
10
+ return "🤖 AI: I received — " + message
11
+
12
+
13
+ # ========================================
14
+ # 🌙 Dark Themed Gradio Interface
15
+ # ========================================
16
+ with gr.Blocks(theme=gr.themes.Base()) as demo:
17
+ gr.HTML("""
18
+ <style>
19
+ body {
20
+ background: linear-gradient(135deg, #0d0d0d 0%, #1a1a1a 100%);
21
+ color: #f0f0f0;
22
+ margin: 0;
23
+ font-family: 'Roboto', sans-serif;
24
+ height: 100vh;
25
+ overflow: hidden;
26
+ }
27
+ .container {
28
+ display: flex;
29
+ height: 100vh;
30
+ }
31
+ .sidebar {
32
+ width: 260px;
33
+ background-color: #2a2a2a;
34
+ border-right: 2px solid #444;
35
+ padding: 20px;
36
+ display: flex;
37
+ flex-direction: column;
38
+ box-shadow: inset -5px 0 10px rgba(0,0,0,0.5);
39
+ }
40
+ .sidebar h2 {
41
+ color: #03dac6;
42
+ font-weight: 400;
43
+ text-align: center;
44
+ margin-bottom: 25px;
45
+ }
46
+ .sidebar button {
47
+ background-color: transparent;
48
+ border: none;
49
+ color: #f0f0f0;
50
+ text-align: left;
51
+ padding: 12px;
52
+ margin-bottom: 8px;
53
+ border-radius: 8px;
54
+ cursor: pointer;
55
+ transition: 0.3s;
56
+ font-size: 15px;
57
+ }
58
+ .sidebar button:hover {
59
+ background-color: #444;
60
+ transform: translateX(4px);
61
+ }
62
+ .main {
63
+ flex: 1;
64
+ display: flex;
65
+ flex-direction: column;
66
+ background-color: transparent;
67
+ }
68
+ .chatbox {
69
+ flex: 1;
70
+ background-color: transparent;
71
+ padding: 20px;
72
+ overflow-y: auto;
73
+ display: flex;
74
+ flex-direction: column;
75
+ }
76
+ .input-area {
77
+ background-color: #2a2a2a;
78
+ padding: 20px;
79
+ border-top: 2px solid #444;
80
+ display: flex;
81
+ align-items: center;
82
+ }
83
+ input[type='text'] {
84
+ flex: 1;
85
+ background-color: #444;
86
+ color: #f0f0f0;
87
+ border: none;
88
+ border-radius: 25px;
89
+ padding: 12px 20px;
90
+ font-size: 15px;
91
+ outline: none;
92
+ }
93
+ button.send-btn {
94
+ margin-left: 10px;
95
+ background: linear-gradient(135deg, #03dac6 0%, #00bfa5 100%);
96
+ border: none;
97
+ color: #0d0d0d;
98
+ font-weight: bold;
99
+ border-radius: 25px;
100
+ padding: 12px 20px;
101
+ cursor: pointer;
102
+ transition: 0.3s;
103
+ }
104
+ button.send-btn:hover {
105
+ transform: scale(1.05);
106
+ box-shadow: 0 0 10px rgba(3, 218, 198, 0.5);
107
+ }
108
+ </style>
109
+ """)
110
+
111
+ # Sidebar
112
+ with gr.Row(elem_classes="container"):
113
+ with gr.Column(elem_classes="sidebar"):
114
+ gr.HTML("<h2>AI Agent</h2>")
115
+ study_tutor = gr.Button("📘 Study Tutor")
116
+ study_planner = gr.Button("🗓️ Study Planner")
117
+ study_advisor = gr.Button("🧠 Study Advisor")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  gr.Markdown("---")
119
+ gr.Markdown(" <small>By Cherry</small>")
120
 
121
+ # Main Chat Section
122
+ with gr.Column(elem_classes="main"):
123
+ chatbot = gr.Chatbot(height=500, show_label=False, elem_classes="chatbox")
124
+ msg = gr.Textbox(placeholder="Type your query here...", show_label=False)
125
+ send = gr.Button("Send", elem_classes="send-btn")
126
 
127
+ def respond(message, history):
128
+ history = history or []
129
+ reply = ai_response(message, history)
130
+ history.append((message, reply))
131
+ return "", history
 
 
 
 
 
 
 
 
 
132
 
133
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
134
+ send.click(respond, [msg, chatbot], [msg, chatbot])
 
 
 
 
135
 
136
+ demo.launch()