Wfafa commited on
Commit
ae3ec54
ยท
verified ยท
1 Parent(s): 202ea3b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -245
app.py CHANGED
@@ -3,14 +3,27 @@ import gradio as gr
3
  import requests
4
  import json
5
 
6
- # Test HF_TOKEN
7
  HF_TOKEN = os.getenv("HF_TOKEN")
8
  if not HF_TOKEN:
9
- print("Error: HF_TOKEN not set. Please set your Hugging Face API token.")
10
  else:
11
  print("HF_TOKEN loaded successfully.")
12
 
13
- # ๐ŸŒ Web search function (unchanged)
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  def search_web(query):
15
  try:
16
  url = "https://api.duckduckgo.com/"
@@ -27,309 +40,119 @@ def search_web(query):
27
  except Exception as e:
28
  return f"Search error: {e}"
29
 
30
- # ๐Ÿง  Memory setup (unchanged)
31
- MEMORY_FILE = "memory.json"
32
-
33
- def load_memory():
34
- if os.path.exists(MEMORY_FILE):
35
- with open(MEMORY_FILE, "r") as f:
36
- return json.load(f)
37
- return []
38
-
39
- def save_memory(memory):
40
- with open(MEMORY_FILE, "w") as f:
41
- json.dump(memory, f)
42
-
43
- memory = load_memory()
44
-
45
- # ๐Ÿ’ฌ Chat function with better error handling
46
  def chat_with_model(message, history, context, file_input=None):
47
- if not isinstance(history, list):
48
  history = []
49
 
50
  if message.lower().startswith("search "):
51
  query = message[7:]
52
  search_result = search_web(query)
53
- history.append((message, f"๐Ÿ”Ž Here's what I found online:\n\n{search_result}"))
 
54
  save_memory(history)
55
  return history, history
56
 
57
  if file_input:
58
- file_name = file_input.name
59
- message += f"\n\n๐Ÿ“Ž (User uploaded a file named '{file_name}')"
60
-
61
- conversation = [
62
- {"role": "system", "content": (
63
- "You are EduAI, a multilingual educational AI assistant created by a Sri Lankan student named Wafa Fazly. "
64
- "When solving math, explain step-by-step like a professional tutor. "
65
- "Use Markdown and LaTeX formatting for equations (use \\[ and \\]). "
66
- "Keep answers neat, structured, and student-friendly."
67
- )}
68
- ]
69
 
70
- for past_user, past_bot in history[-5:]:
71
- conversation.append({"role": "user", "content": past_user})
72
- conversation.append({"role": "assistant", "content": past_bot})
73
 
74
- conversation.append({"role": "user", "content": message})
 
75
 
76
  try:
77
- # Primary API call
78
  response = requests.post(
79
  "https://router.huggingface.co/v1/chat/completions",
80
  headers={
81
  "Authorization": f"Bearer {HF_TOKEN}",
82
  "Content-Type": "application/json"
83
  },
84
- json={
85
- "model": "deepseek-ai/DeepSeek-V3.2-Exp:novita",
86
- "messages": conversation
87
- }
88
  )
89
  if response.status_code != 200:
90
  raise Exception(f"API Error: {response.status_code} - {response.text}")
91
-
92
- data = response.json()
93
- reply = data["choices"][0]["message"]["content"]
94
 
 
 
 
95
  reply = reply.replace("Step", "\n\n**Step").replace(":", ":**").replace("\\[", "\n\n\\[").replace("\\]", "\\]\n\n")
96
 
97
- history.append((message, reply))
 
98
  save_memory(history)
99
  return history, history
100
 
101
  except Exception as e:
102
  print("Backend Error:", e)
103
- error_msg = "๐Ÿ˜… EduAI is having trouble connecting right now. Check your HF_TOKEN or try again later!"
104
- history.append((message, error_msg))
105
  return history, history
106
 
107
- # Rest of the code (unchanged, including UI and CSS)
108
-
109
- # ๐Ÿ“˜ Sidebar context update
110
  def update_context(choice):
111
  if not choice:
112
  return "๐Ÿ“˜ **You are in General Mode.** Ask EduAI anything about your studies!"
113
  return f"๐Ÿ“˜ **You selected {choice} mode.** Ask anything related to this topic!"
114
 
115
- # ๐Ÿงน Clear chat memory
116
  def clear_memory():
117
  if os.path.exists(MEMORY_FILE):
118
  os.remove(MEMORY_FILE)
119
  return [], "๐Ÿงน Chat memory cleared! Start fresh."
120
 
121
- # ๐Ÿ–Œ Custom CSS (unchanged)
122
  custom_css = """
123
- @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;600&display=swap');
124
-
125
- body {
126
- font-family: 'Roboto', sans-serif;
127
- margin: 0;
128
- padding: 0;
129
- background: #1e1e1e;
130
- color: #e0e0e0;
131
- min-height: 100vh;
132
- }
133
- .gradio-container {
134
- background: transparent;
135
- box-shadow: none;
136
- }
137
- .header-title {
138
- font-size: 36px;
139
- text-align: center;
140
- margin-bottom: 20px;
141
- font-weight: 600;
142
- color: #007BFF;
143
- text-shadow: 0 0 10px rgba(0, 123, 255, 0.5);
144
- }
145
- .sidebar {
146
- background: #2a2a2a;
147
- padding: 20px;
148
- border-radius: 12px;
149
- box-shadow: 0 4px 12px rgba(0,0,0,0.5);
150
- border: 1px solid #333;
151
- }
152
- .menu-title {
153
- font-size: 20px;
154
- font-weight: 500;
155
- margin-bottom: 15px;
156
- color: #007BFF;
157
- }
158
- .accordion {
159
- border-radius: 10px;
160
- margin-bottom: 10px;
161
- box-shadow: 0 2px 6px rgba(0,0,0,0.3);
162
- }
163
- .accordion-header {
164
- background: #333;
165
- color: #e0e0e0;
166
- border-radius: 10px;
167
- padding: 12px;
168
- font-weight: 500;
169
- cursor: pointer;
170
- transition: background 0.3s;
171
- }
172
- .accordion-header:hover {
173
- background: #007BFF;
174
- color: #1e1e1e;
175
- }
176
- .main-chat {
177
- padding: 20px;
178
- background: #1e1e1e;
179
- }
180
- .context-box {
181
- background: #2a2a2a;
182
- padding: 15px;
183
- border-radius: 10px;
184
- box-shadow: 0 2px 6px rgba(0,0,0,0.3);
185
- margin-bottom: 15px;
186
- border: 1px solid #333;
187
- color: #e0e0e0;
188
- }
189
- .chatbox {
190
- border-radius: 10px;
191
- box-shadow: 0 2px 6px rgba(0,0,0,0.3);
192
- background: #252525;
193
- border: 1px solid #333;
194
- }
195
- .chatbox .message.user {
196
- background: #007BFF;
197
- color: #1e1e1e;
198
- border-radius: 12px;
199
- padding: 12px 15px;
200
- margin: 8px 0;
201
- box-shadow: 0 2px 6px rgba(0, 123, 255, 0.3);
202
- }
203
- .chatbox .message.bot {
204
- background: #333;
205
- color: #e0e0e0;
206
- border-radius: 12px;
207
- padding: 12px 15px;
208
- margin: 8px 0;
209
- box-shadow: 0 2px 6px rgba(0,0,0,0.3);
210
- }
211
- .input-row {
212
- display: flex;
213
- align-items: center;
214
- gap: 10px;
215
- }
216
- .chat-input {
217
- flex: 1;
218
- border-radius: 10px;
219
- padding: 12px;
220
- border: 1px solid #555;
221
- background: #2a2a2a;
222
- color: #e0e0e0;
223
- transition: border-color 0.3s;
224
- }
225
- .chat-input:focus {
226
- border-color: #007BFF;
227
- outline: none;
228
- }
229
- .file-upload {
230
- width: 40px;
231
- height: 40px;
232
- border: 1px solid #555;
233
- border-radius: 10px;
234
- background: #2a2a2a;
235
- color: #e0e0e0;
236
- display: flex;
237
- align-items: center;
238
- justify-content: center;
239
- cursor: pointer;
240
- transition: background 0.3s;
241
- font-size: 18px;
242
- }
243
- .file-upload:hover {
244
- background: #007BFF;
245
- color: #1e1e1e;
246
- }
247
- .btn-clear {
248
- background: #f44336;
249
- color: white;
250
- border-radius: 10px;
251
- padding: 10px 15px;
252
- border: none;
253
- font-weight: 500;
254
- cursor: pointer;
255
- transition: background 0.3s;
256
- }
257
- .btn-clear:hover {
258
- background: #d32f2f;
259
- }
260
- .about-text {
261
- font-size: 14px;
262
- color: #aaa;
263
- line-height: 1.5;
264
- }
265
- .radio {
266
- margin: 10px 0;
267
- }
268
- .radio label {
269
- color: #e0e0e0;
270
- }
271
  """
272
 
273
- # ๐ŸŽจ Gradio Interface (unchanged)
274
  with gr.Blocks(theme=gr.themes.Base(), css=custom_css) as iface:
275
- gr.Markdown("# ๐ŸŽ“ **EduAI โ€” Your Professional Study Companion**", elem_classes="header-title")
276
 
277
  with gr.Row():
 
278
  with gr.Column(scale=1, min_width=250, elem_classes="sidebar"):
279
  gr.Markdown("### ๐Ÿงญ **Main Menu**", elem_classes="menu-title")
280
 
281
  with gr.Accordion("๐Ÿ“š Subject Tutor", open=False):
282
- subj = gr.Radio(
283
- ["Science ๐Ÿงช", "ICT ๐Ÿ’ป", "English ๐Ÿ“˜", "Mathematics โž—"],
284
- label="Choose a subject",
285
- type="index"
286
- )
287
 
288
  with gr.Accordion("๐Ÿ—“ Study Planner", open=False):
289
- planner = gr.Radio(
290
- ["View Plan ๐Ÿ“…", "Add Task โœ๏ธ", "Study Tips ๐Ÿ’ก"],
291
- label="Planner Options",
292
- type="index"
293
- )
294
 
295
  with gr.Accordion("๐ŸŒ Languages", open=False):
296
- lang = gr.Radio(
297
- ["Learn Sinhala ๐Ÿ‡ฑ๐Ÿ‡ฐ", "Learn Tamil ๐Ÿ‡ฎ๐Ÿ‡ณ", "Learn English ๐Ÿ‡ฌ๐Ÿ‡ง", "Learn Spanish ๐Ÿ‡ช๐Ÿ‡ธ"],
298
- label="Language Options",
299
- type="index"
300
- )
301
 
302
  with gr.Accordion("โš™๏ธ Settings", open=False):
303
  clear_btn = gr.Button("๐Ÿงน Clear Memory", elem_classes="btn-clear")
304
 
305
  with gr.Accordion("๐Ÿ‘ฉโ€๐ŸŽ“ About", open=False):
306
- gr.Markdown("""
307
- EduAI โ€“ developed by **Wafa Fazly** using a pre-trained AI model.
308
- Helps learners understand **Science, ICT, English, and more** in a simple, friendly way! ๐Ÿ’ฌ
309
- """, elem_classes="about-text")
310
 
 
311
  with gr.Column(scale=4, elem_classes="main-chat"):
312
- context_display = gr.Markdown(
313
- "๐Ÿ“˜ **You are in General Mode.** Ask EduAI anything about your studies!",
314
- elem_classes="context-box"
315
- )
316
-
317
- chatbot = gr.Chatbot(
318
- label="EduAI Chat",
319
- height=500,
320
- render_markdown=True,
321
- type="messages",
322
- latex_delimiters=[{"left": "$$", "right": "$$", "display": True}, {"left": "\\[", "right": "\\]", "display": True}]
323
- )
324
-
325
- with gr.Row(elem_classes="input-row"):
326
- msg = gr.Textbox(label="Ask EduAI:", placeholder="Type your question here...", elem_classes="chat-input", show_label=False)
327
- file_input = gr.File(label="๐Ÿ“Ž", file_types=[".pdf", ".docx", ".png", ".jpg"], elem_classes="file-upload", show_label=False)
328
-
329
- subj.change(update_context, inputs=subj, outputs=context_display)
330
- planner.change(update_context, inputs=planner, outputs=context_display)
331
- lang.change(update_context, inputs=lang, outputs=context_display)
332
- msg.submit(chat_with_model, inputs=[msg, chatbot, context_display, file_input], outputs=[chatbot, chatbot])
333
- clear_btn.click(clear_memory, outputs=[chatbot, context_display])
334
-
335
- iface.launch()
 
3
  import requests
4
  import json
5
 
6
+ # Hugging Face Token
7
  HF_TOKEN = os.getenv("HF_TOKEN")
8
  if not HF_TOKEN:
9
+ print("Error: HF_TOKEN not set.")
10
  else:
11
  print("HF_TOKEN loaded successfully.")
12
 
13
+ # Memory file
14
+ MEMORY_FILE = "memory.json"
15
+
16
+ def load_memory():
17
+ if os.path.exists(MEMORY_FILE):
18
+ with open(MEMORY_FILE, "r") as f:
19
+ return json.load(f)
20
+ return []
21
+
22
+ def save_memory(memory):
23
+ with open(MEMORY_FILE, "w") as f:
24
+ json.dump(memory, f)
25
+
26
+ # Web search
27
  def search_web(query):
28
  try:
29
  url = "https://api.duckduckgo.com/"
 
40
  except Exception as e:
41
  return f"Search error: {e}"
42
 
43
+ # Chat function with messages format
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  def chat_with_model(message, history, context, file_input=None):
45
+ if history is None:
46
  history = []
47
 
48
  if message.lower().startswith("search "):
49
  query = message[7:]
50
  search_result = search_web(query)
51
+ history.append({"role": "user", "content": message})
52
+ history.append({"role": "assistant", "content": f"๐Ÿ”Ž Here's what I found online:\n\n{search_result}"})
53
  save_memory(history)
54
  return history, history
55
 
56
  if file_input:
57
+ message += f"\n\n๐Ÿ“Ž (User uploaded a file named '{file_input.name}')"
 
 
 
 
 
 
 
 
 
 
58
 
59
+ # Add user message
60
+ history.append({"role": "user", "content": message})
 
61
 
62
+ # Build conversation for API
63
+ conversation = [{"role": m["role"], "content": m["content"]} for m in history]
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={"model": "deepseek-ai/DeepSeek-V3.2-Exp:novita", "messages": conversation}
 
 
 
73
  )
74
  if response.status_code != 200:
75
  raise Exception(f"API Error: {response.status_code} - {response.text}")
 
 
 
76
 
77
+ reply = response.json()["choices"][0]["message"]["content"]
78
+
79
+ # Format math nicely
80
  reply = reply.replace("Step", "\n\n**Step").replace(":", ":**").replace("\\[", "\n\n\\[").replace("\\]", "\\]\n\n")
81
 
82
+ # Add assistant reply
83
+ history.append({"role": "assistant", "content": reply})
84
  save_memory(history)
85
  return history, history
86
 
87
  except Exception as e:
88
  print("Backend Error:", e)
89
+ error_msg = "๐Ÿ˜… EduAI is having trouble connecting. Check HF_TOKEN or try again later!"
90
+ history.append({"role": "assistant", "content": error_msg})
91
  return history, history
92
 
93
+ # Sidebar context update
 
 
94
  def update_context(choice):
95
  if not choice:
96
  return "๐Ÿ“˜ **You are in General Mode.** Ask EduAI anything about your studies!"
97
  return f"๐Ÿ“˜ **You selected {choice} mode.** Ask anything related to this topic!"
98
 
99
+ # Clear memory
100
  def clear_memory():
101
  if os.path.exists(MEMORY_FILE):
102
  os.remove(MEMORY_FILE)
103
  return [], "๐Ÿงน Chat memory cleared! Start fresh."
104
 
105
+ # Custom CSS for professional look
106
  custom_css = """
107
+ @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap');
108
+ body { font-family: 'Roboto', sans-serif; background:#1e1e1e; color:#e0e0e0; min-height:100vh; }
109
+ .header-title { font-size:36px; text-align:center; margin-bottom:20px; color:#007BFF; font-weight:700; text-shadow:0 0 10px rgba(0,123,255,0.5); }
110
+ .sidebar { background:#2a2a2a; padding:20px; border-radius:12px; box-shadow:0 4px 12px rgba(0,0,0,0.5); border:1px solid #333; }
111
+ .menu-title { font-size:20px; font-weight:500; margin-bottom:15px; color:#007BFF; }
112
+ .accordion { background:#2a2a2a; border-radius:12px; padding:10px; margin-bottom:10px; box-shadow:0 3px 8px rgba(0,0,0,0.5); }
113
+ .accordion-header { background:#333; color:#e0e0e0; border-radius:10px; padding:12px; font-weight:500; cursor:pointer; transition:0.3s; }
114
+ .accordion-header:hover { background:#007BFF; color:#1e1e1e; }
115
+ .main-chat { padding:20px; background:#1e1e1e; }
116
+ .context-box { background:#2a2a2a; padding:15px; border-radius:10px; box-shadow:0 2px 6px rgba(0,0,0,0.3); margin-bottom:15px; border:1px solid #333; color:#e0e0e0; }
117
+ .chatbox .message.user { background:#007BFF; color:#fff; border-radius:20px; padding:12px 18px; margin:8px 0; }
118
+ .chatbox .message.bot { background:#333; color:#e0e0e0; border-radius:20px; padding:12px 18px; margin:8px 0; }
119
+ .input-row { display:flex; gap:10px; }
120
+ .chat-input { flex:1; border-radius:12px; padding:12px; border:1px solid #555; background:#2a2a2a; color:#e0e0e0; }
121
+ .chat-input:focus { border-color:#007BFF; outline:none; }
122
+ .btn-send { background:#7c3aed; color:#fff; border-radius:12px; padding:12px 18px; border:none; cursor:pointer; transition:0.3s; }
123
+ .btn-send:hover { background:#5b21b6; }
124
+ .file-upload { width:50px; height:50px; border:1px solid #555; border-radius:12px; background:#2a2a2a; display:flex; align-items:center; justify-content:center; cursor:pointer; font-size:20px; color:#e0e0e0; transition:0.3s; }
125
+ .file-upload:hover { background:#007BFF; color:#1e1e1e; }
126
+ .btn-clear { background:#f44336; color:white; border-radius:12px; padding:10px 15px; border:none; cursor:pointer; transition:0.3s; }
127
+ .btn-clear:hover { background:#d32f2f; }
128
+ .about-text { font-size:14px; color:#aaa; line-height:1.5; }
129
+ .radio label { color:#e0e0e0; margin:8px 0; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  """
131
 
132
+ # Launch Gradio UI
133
  with gr.Blocks(theme=gr.themes.Base(), css=custom_css) as iface:
134
+ gr.Markdown("# ๐ŸŽ“ **EduAI โ€” Professional Study Companion**", elem_classes="header-title")
135
 
136
  with gr.Row():
137
+ # Sidebar
138
  with gr.Column(scale=1, min_width=250, elem_classes="sidebar"):
139
  gr.Markdown("### ๐Ÿงญ **Main Menu**", elem_classes="menu-title")
140
 
141
  with gr.Accordion("๐Ÿ“š Subject Tutor", open=False):
142
+ subj = gr.Radio(["Science ๐Ÿงช", "ICT ๐Ÿ’ป", "English ๐Ÿ“˜", "Mathematics โž—"], label="Choose a subject", type="index")
 
 
 
 
143
 
144
  with gr.Accordion("๐Ÿ—“ Study Planner", open=False):
145
+ planner = gr.Radio(["View Plan ๐Ÿ“…", "Add Task โœ๏ธ", "Study Tips ๐Ÿ’ก"], label="Planner Options", type="index")
 
 
 
 
146
 
147
  with gr.Accordion("๐ŸŒ Languages", open=False):
148
+ lang = gr.Radio(["Learn Sinhala ๐Ÿ‡ฑ๐Ÿ‡ฐ","Learn Tamil ๐Ÿ‡ฎ๐Ÿ‡ณ","Learn English ๐Ÿ‡ฌ๐Ÿ‡ง","Learn Spanish ๐Ÿ‡ช๐Ÿ‡ธ"], label="Language Options", type="index")
 
 
 
 
149
 
150
  with gr.Accordion("โš™๏ธ Settings", open=False):
151
  clear_btn = gr.Button("๐Ÿงน Clear Memory", elem_classes="btn-clear")
152
 
153
  with gr.Accordion("๐Ÿ‘ฉโ€๐ŸŽ“ About", open=False):
154
+ gr.Markdown("EduAI โ€“ developed by **Wafa Fazly** using a pre-trained AI model. Helps learners understand **Science, ICT, English, and more**.", elem_classes="about-text")
 
 
 
155
 
156
+ # Main chat
157
  with gr.Column(scale=4, elem_classes="main-chat"):
158
+ context_display = gr.Markdown("๐Ÿ“˜ **You are in General Mode.** Ask EduAI anything