Wfafa commited on
Commit
75fd541
ยท
verified ยท
1 Parent(s): 41fd142

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -86
app.py CHANGED
@@ -2,7 +2,7 @@ import os
2
  import gradio as gr
3
  import requests
4
  import json
5
- import re
6
 
7
  # ๐ŸŒ Web search function
8
  def search_web(query):
@@ -43,20 +43,17 @@ def chat_with_model(message, history, context, file_input=None):
43
  if not isinstance(history, list):
44
  history = []
45
 
46
- # ๐ŸŒ Web search mode
47
  if message.lower().startswith("search "):
48
  query = message[7:]
49
  search_result = search_web(query)
50
  history.append((message, f"๐Ÿ”Ž Here's what I found online:\n\n{search_result}"))
51
  save_memory(history)
52
- return history, ""
53
 
54
- # ๐Ÿ“‚ If file is uploaded
55
  if file_input:
56
- file_name = os.path.basename(file_input.name)
57
  message += f"\n\n๐Ÿ“Ž (User uploaded a file named '{file_name}')"
58
 
59
- # ๐Ÿง  Build conversation
60
  conversation = [
61
  {"role": "system", "content": (
62
  "You are EduAI, a multilingual educational AI assistant created by a Sri Lankan student named Wafa Fazly. "
@@ -72,7 +69,6 @@ def chat_with_model(message, history, context, file_input=None):
72
 
73
  conversation.append({"role": "user", "content": message})
74
 
75
- # ๐Ÿš€ Send to Hugging Face model
76
  try:
77
  response = requests.post(
78
  "https://router.huggingface.co/v1/chat/completions",
@@ -81,7 +77,7 @@ def chat_with_model(message, history, context, file_input=None):
81
  "Content-Type": "application/json"
82
  },
83
  json={
84
- "model": "deepseek-ai/DeepSeek-V2.5",
85
  "messages": conversation
86
  }
87
  )
@@ -89,19 +85,23 @@ def chat_with_model(message, history, context, file_input=None):
89
  data = response.json()
90
  reply = data["choices"][0]["message"]["content"]
91
 
92
- # ๐Ÿงฎ Clean up math formatting
93
- reply = re.sub(r"\bStep (\d+):", r"\n\n**Step \1:**", reply)
94
  reply = reply.replace("\\[", "\n\n\\[")
95
  reply = reply.replace("\\]", "\\]\n\n")
96
 
 
 
 
97
  history.append((message, reply))
98
  save_memory(history)
99
- return history, ""
100
 
101
  except Exception as e:
102
  print("Error:", e)
103
  history.append((message, "๐Ÿ˜… EduAI is having trouble connecting right now. Please try again later!"))
104
- return history, ""
 
105
 
106
  # ๐Ÿ“˜ Sidebar context update
107
  def update_context(choice):
@@ -109,81 +109,34 @@ def update_context(choice):
109
  return "๐Ÿ“˜ **You are in General Mode.** Ask EduAI anything about your studies!"
110
  return f"๐Ÿ“˜ **You selected {choice} mode.** Ask anything related to this topic!"
111
 
 
112
  # ๐Ÿงน Clear chat memory
113
  def clear_memory():
114
  if os.path.exists(MEMORY_FILE):
115
  os.remove(MEMORY_FILE)
116
  return [], "๐Ÿงน Chat memory cleared! Start fresh."
117
 
118
- # ๐Ÿงฉ Dynamic MCQ Quiz Generator
119
- def generate_dynamic_quiz(topic):
120
- try:
121
- if not topic.strip():
122
- return [gr.Markdown("โš ๏ธ Please enter a topic to generate the quiz.")]
123
-
124
- prompt = f"""
125
- Create 5 multiple-choice questions about "{topic}".
126
- Each question should have 4 options (A, B, C, D) and only one correct answer.
127
- Format the response in JSON like this:
128
- [
129
- {{
130
- "question": "...",
131
- "options": ["...", "...", "...", "..."],
132
- "answer": "..."
133
- }},
134
- ...
135
- ]
136
- """
137
 
138
- response = requests.post(
139
- "https://router.huggingface.co/v1/chat/completions",
140
- headers={
141
- "Authorization": f"Bearer {HF_TOKEN}",
142
- "Content-Type": "application/json"
143
- },
144
- json={
145
- "model": "deepseek-ai/DeepSeek-V2.5",
146
- "messages": [{"role": "user", "content": prompt}]
147
- }
148
- )
149
 
150
- data = response.json()
151
- raw_text = data["choices"][0]["message"]["content"]
152
-
153
- # ๐Ÿงฉ Try parsing JSON
154
- try:
155
- quiz_data = json.loads(raw_text)
156
- except:
157
- quiz_data = []
158
- for block in raw_text.split("\n\n"):
159
- if "?" in block:
160
- parts = block.split("\n")
161
- q = parts[0]
162
- opts = [p.strip("- ").strip() for p in parts[1:5] if p.strip()]
163
- if len(opts) == 4:
164
- quiz_data.append({
165
- "question": q,
166
- "options": opts,
167
- "answer": ""
168
- })
169
-
170
- # ๐ŸŽฏ Build UI dynamically
171
- quiz_elements = []
172
- for q in quiz_data:
173
- quiz_elements.append(gr.Markdown(f"### โ“ {q['question']}"))
174
- quiz_elements.append(gr.CheckboxGroup(
175
- choices=q["options"],
176
- label="Select your answer:",
177
- interactive=True
178
- ))
179
-
180
- if not quiz_elements:
181
- return [gr.Markdown("๐Ÿ˜… Couldn't generate a proper quiz. Try another topic!")]
182
-
183
- return quiz_elements
184
 
185
- except Exception as e:
186
- return [gr.Markdown(f"Error generating quiz: {e}")]
187
 
188
  # ๐ŸŽจ Gradio Interface
189
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="violet")) as iface:
@@ -211,11 +164,9 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="violet")) as iface:
211
  label="Language Options"
212
  )
213
 
214
- # ๐Ÿงฉ MCQ Quiz Generator
215
- with gr.Accordion("๐Ÿงฉ MCQ Quiz Generator", open=False):
216
- quiz_topic = gr.Textbox(label="Enter a topic (e.g., Photosynthesis, AI, Newton's Laws):")
217
- generate_quiz_btn = gr.Button("Generate Quiz ๐Ÿง ")
218
- quiz_output = gr.Column()
219
 
220
  with gr.Accordion("โš™๏ธ Settings", open=False):
221
  clear_btn = gr.Button("๐Ÿงน Clear Memory")
@@ -243,9 +194,8 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="violet")) as iface:
243
  subj.change(update_context, inputs=subj, outputs=context_display)
244
  planner.change(update_context, inputs=planner, outputs=context_display)
245
  lang.change(update_context, inputs=lang, outputs=context_display)
246
- send.click(chat_with_model, inputs=[msg, chatbot, context_display, file_input], outputs=[chatbot, msg])
247
- msg.submit(chat_with_model, inputs=[msg, chatbot, context_display, file_input], outputs=[chatbot, msg])
248
  clear_btn.click(clear_memory, outputs=[chatbot, context_display])
249
- generate_quiz_btn.click(generate_dynamic_quiz, inputs=quiz_topic, outputs=quiz_output)
250
 
251
  iface.launch()
 
2
  import gradio as gr
3
  import requests
4
  import json
5
+ import random
6
 
7
  # ๐ŸŒ Web search function
8
  def search_web(query):
 
43
  if not isinstance(history, list):
44
  history = []
45
 
 
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
  if file_input:
54
+ file_name = file_input.name
55
  message += f"\n\n๐Ÿ“Ž (User uploaded a file named '{file_name}')"
56
 
 
57
  conversation = [
58
  {"role": "system", "content": (
59
  "You are EduAI, a multilingual educational AI assistant created by a Sri Lankan student named Wafa Fazly. "
 
69
 
70
  conversation.append({"role": "user", "content": message})
71
 
 
72
  try:
73
  response = requests.post(
74
  "https://router.huggingface.co/v1/chat/completions",
 
77
  "Content-Type": "application/json"
78
  },
79
  json={
80
+ "model": "deepseek-ai/DeepSeek-V3.2-Exp:novita",
81
  "messages": conversation
82
  }
83
  )
 
85
  data = response.json()
86
  reply = data["choices"][0]["message"]["content"]
87
 
88
+ reply = reply.replace("Step", "\n\n**Step")
89
+ reply = reply.replace(":", ":**")
90
  reply = reply.replace("\\[", "\n\n\\[")
91
  reply = reply.replace("\\]", "\\]\n\n")
92
 
93
+ if "\\" in reply or "log_" in reply or "^" in reply:
94
+ reply = f"{reply}"
95
+
96
  history.append((message, reply))
97
  save_memory(history)
98
+ return history, history
99
 
100
  except Exception as e:
101
  print("Error:", e)
102
  history.append((message, "๐Ÿ˜… EduAI is having trouble connecting right now. Please try again later!"))
103
+ return history, history
104
+
105
 
106
  # ๐Ÿ“˜ Sidebar context update
107
  def update_context(choice):
 
109
  return "๐Ÿ“˜ **You are in General Mode.** Ask EduAI anything about your studies!"
110
  return f"๐Ÿ“˜ **You selected {choice} mode.** Ask anything related to this topic!"
111
 
112
+
113
  # ๐Ÿงน Clear chat memory
114
  def clear_memory():
115
  if os.path.exists(MEMORY_FILE):
116
  os.remove(MEMORY_FILE)
117
  return [], "๐Ÿงน Chat memory cleared! Start fresh."
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
+ # ๐Ÿง  MCQ QUIZ GENERATOR
121
+ quiz_data = [
122
+ {"question": "Which planet is known as the Red Planet?", "options": ["Earth", "Mars", "Venus", "Jupiter"], "answer": "Mars"},
123
+ {"question": "What is the chemical symbol for water?", "options": ["H2O", "O2", "CO2", "NaCl"], "answer": "H2O"},
124
+ {"question": "What is 5 ร— 6?", "options": ["11", "30", "25", "36"], "answer": "30"},
125
+ {"question": "Which gas do humans breathe in to survive?", "options": ["Carbon dioxide", "Oxygen", "Nitrogen", "Hydrogen"], "answer": "Oxygen"},
126
+ {"question": "What is the largest planet in our Solar System?", "options": ["Earth", "Mars", "Jupiter", "Saturn"], "answer": "Jupiter"}
127
+ ]
 
 
 
128
 
129
+ def generate_quiz():
130
+ selected = random.sample(quiz_data, 3)
131
+ quiz_html = ""
132
+ for i, q in enumerate(selected, 1):
133
+ quiz_html += f"<div><b>{i}. {q['question']}</b><br>"
134
+ for opt in q['options']:
135
+ quiz_html += f"<input type='checkbox' name='q{i}' value='{opt}'> {opt}<br>"
136
+ quiz_html += "<br></div>"
137
+ quiz_html += "<br><b>โœ… Select your answers and review!</b>"
138
+ return quiz_html
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
 
 
140
 
141
  # ๐ŸŽจ Gradio Interface
142
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="violet")) as iface:
 
164
  label="Language Options"
165
  )
166
 
167
+ with gr.Accordion("๐Ÿง  MCQ Quiz Generator", open=False):
168
+ gen_btn = gr.Button("๐ŸŽฏ Generate Quiz")
169
+ quiz_output = gr.HTML("<i>Click 'Generate Quiz' to start!</i>")
 
 
170
 
171
  with gr.Accordion("โš™๏ธ Settings", open=False):
172
  clear_btn = gr.Button("๐Ÿงน Clear Memory")
 
194
  subj.change(update_context, inputs=subj, outputs=context_display)
195
  planner.change(update_context, inputs=planner, outputs=context_display)
196
  lang.change(update_context, inputs=lang, outputs=context_display)
197
+ send.click(chat_with_model, inputs=[msg, chatbot, context_display, file_input], outputs=[chatbot, chatbot])
 
198
  clear_btn.click(clear_memory, outputs=[chatbot, context_display])
199
+ gen_btn.click(generate_quiz, outputs=quiz_output)
200
 
201
  iface.launch()