Wfafa commited on
Commit
e025ca8
·
verified ·
1 Parent(s): c243479

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -45
app.py CHANGED
@@ -2,15 +2,13 @@ import os
2
  import gradio as gr
3
  import requests
4
  import json
5
- import random
6
 
7
- # Hugging Face API token
8
- HF_TOKEN = os.getenv("HF_TOKEN")
9
 
10
- # =========================
11
  # AI response via DeepSeek
12
- # =========================
13
- def ai_response(message, history=None):
14
  if history is None:
15
  history = []
16
 
@@ -18,10 +16,9 @@ def ai_response(message, history=None):
18
  "You are EduAI, a professional multilingual educational assistant. "
19
  "Explain clearly with examples, use step-by-step for math, and Markdown/LaTeX for equations."
20
  )}]
21
-
22
- for past_user, past_bot in history[-5:]:
23
- conversation.append({"role": "user", "content": past_user})
24
- conversation.append({"role": "assistant", "content": past_bot})
25
 
26
  conversation.append({"role": "user", "content": message})
27
 
@@ -37,26 +34,29 @@ def ai_response(message, history=None):
37
  "messages": conversation
38
  }
39
  )
 
40
  data = response.json()
41
  reply = data["choices"][0]["message"]["content"]
42
- history.append((message, reply))
43
- return history, reply
44
  except Exception as e:
45
- history.append((message, f"❌ Error contacting model: {e}"))
46
- return history, history[-1][1]
 
 
47
 
48
- # =========================
49
- # MCQ Generator (AI-based)
50
- # =========================
51
  def generate_mcq(subject):
52
- prompt = f"Create 3 multiple-choice questions with 4 options each and the correct answer for {subject}. Return as JSON like: [{{'question':'...','options':['..'],'answer':'..'}}, ...]"
53
- history, reply = ai_response(prompt)
54
  try:
55
  mcqs = json.loads(reply)
 
 
56
  except:
57
- return f" Error generating MCQs: {reply}"
58
 
59
- quiz_html = "<div style='font-family:Poppins, sans-serif; color:#EEE;'>"
60
  for i, q in enumerate(mcqs, 1):
61
  quiz_html += f"<div style='margin-bottom:15px; padding:12px; border-radius:10px; background:#2a2a2a;'>"
62
  quiz_html += f"<b style='color:#7C3AED;'>{i}. {q['question']}</b><br>"
@@ -67,20 +67,23 @@ def generate_mcq(subject):
67
  quiz_html += "</div>"
68
  return quiz_html
69
 
70
- # =========================
71
  # Study Adviser
72
- # =========================
73
  def study_adviser(question):
74
- history, answer = ai_response(f"Give a professional study advice: {question}")
 
 
75
  return answer
76
 
77
- # =========================
78
  # Study Planner
79
- # =========================
80
  planner_tasks = []
81
 
82
  def add_task(task):
83
- planner_tasks.append(task)
 
84
  return "\n".join([f"- {t}" for t in planner_tasks])
85
 
86
  def view_plan():
@@ -88,11 +91,11 @@ def view_plan():
88
  return "No tasks added yet."
89
  return "\n".join([f"- {t}" for t in planner_tasks])
90
 
91
- # =========================
92
  # Gradio UI
93
- # =========================
94
  custom_css = """
95
- body {background:#121212; color:#EEE; font-family:Poppins, sans-serif;}
96
  button.primary {background:#7C3AED; color:white; border-radius:8px; padding:5px 12px;}
97
  button.primary:hover {background:#6D28D9;}
98
  .gradio-container {background:#121212;}
@@ -132,23 +135,12 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Dark()) as iface:
132
  user_input = gr.Textbox(label="Type your question:")
133
  send_btn = gr.Button("Send", elem_classes="primary")
134
 
135
- # =========================
136
- # Event Bindings
137
- # =========================
138
- # Study Tutor
139
- tutor_btn.click(ai_response, inputs=[tutor_input, gr.State(value=[])], outputs=[gr.State(value=[]), tutor_output])
140
-
141
- # MCQ Generator
142
  mcq_btn.click(generate_mcq, inputs=[mcq_subject], outputs=[mcq_output])
143
-
144
- # Study Adviser
145
  adviser_btn.click(study_adviser, inputs=[adviser_input], outputs=[adviser_output])
146
-
147
- # Study Planner
148
  add_task_btn.click(add_task, inputs=[task_input], outputs=[planner_output])
149
- view_plan_btn.click(view_plan, outputs=[planner_output])
150
-
151
- # Chatbot
152
- send_btn.click(ai_response, inputs=[user_input, gr.State(value=[])], outputs=[gr.State(value=[]), chatbot_display])
153
 
154
  iface.launch()
 
2
  import gradio as gr
3
  import requests
4
  import json
 
5
 
6
+ HF_TOKEN = os.getenv("HF_TOKEN") # Hugging Face token
 
7
 
8
+ # ----------------------------
9
  # AI response via DeepSeek
10
+ # ----------------------------
11
+ def ai_response(message, history):
12
  if history is None:
13
  history = []
14
 
 
16
  "You are EduAI, a professional multilingual educational assistant. "
17
  "Explain clearly with examples, use step-by-step for math, and Markdown/LaTeX for equations."
18
  )}]
19
+ for item in history[-5:]:
20
+ conversation.append({"role": "user", "content": item["user"]})
21
+ conversation.append({"role": "assistant", "content": item["bot"]})
 
22
 
23
  conversation.append({"role": "user", "content": message})
24
 
 
34
  "messages": conversation
35
  }
36
  )
37
+ response.raise_for_status()
38
  data = response.json()
39
  reply = data["choices"][0]["message"]["content"]
 
 
40
  except Exception as e:
41
+ reply = f"❌ Error: {e}"
42
+
43
+ history.append({"user": message, "bot": reply})
44
+ return history, reply
45
 
46
+ # ----------------------------
47
+ # MCQ Generator
48
+ # ----------------------------
49
  def generate_mcq(subject):
50
+ prompt = f"Create 3 multiple-choice questions with 4 options each and the correct answer for {subject}. Return as JSON like: [{'question':'...','options':['..'],'answer':'..'}, ...]"
51
+ _, reply = ai_response(prompt, [])
52
  try:
53
  mcqs = json.loads(reply)
54
+ if not isinstance(mcqs, list):
55
+ raise ValueError("Invalid JSON")
56
  except:
57
+ return f"<p style='color:red;'>❌ Error generating MCQs: AI output invalid.</p>"
58
 
59
+ quiz_html = "<div style='font-family:Poppins,sans-serif; color:#EEE;'>"
60
  for i, q in enumerate(mcqs, 1):
61
  quiz_html += f"<div style='margin-bottom:15px; padding:12px; border-radius:10px; background:#2a2a2a;'>"
62
  quiz_html += f"<b style='color:#7C3AED;'>{i}. {q['question']}</b><br>"
 
67
  quiz_html += "</div>"
68
  return quiz_html
69
 
70
+ # ----------------------------
71
  # Study Adviser
72
+ # ----------------------------
73
  def study_adviser(question):
74
+ if not question.strip():
75
+ return "Please enter a question for study advice."
76
+ _, answer = ai_response(f"Give a professional study advice: {question}", [])
77
  return answer
78
 
79
+ # ----------------------------
80
  # Study Planner
81
+ # ----------------------------
82
  planner_tasks = []
83
 
84
  def add_task(task):
85
+ if task.strip():
86
+ planner_tasks.append(task.strip())
87
  return "\n".join([f"- {t}" for t in planner_tasks])
88
 
89
  def view_plan():
 
91
  return "No tasks added yet."
92
  return "\n".join([f"- {t}" for t in planner_tasks])
93
 
94
+ # ----------------------------
95
  # Gradio UI
96
+ # ----------------------------
97
  custom_css = """
98
+ body {background:#121212; color:#EEE; font-family:Poppins,sans-serif;}
99
  button.primary {background:#7C3AED; color:white; border-radius:8px; padding:5px 12px;}
100
  button.primary:hover {background:#6D28D9;}
101
  .gradio-container {background:#121212;}
 
135
  user_input = gr.Textbox(label="Type your question:")
136
  send_btn = gr.Button("Send", elem_classes="primary")
137
 
138
+ # Bind buttons
139
+ tutor_btn.click(lambda msg: ai_response(msg, [])[1], inputs=[tutor_input], outputs=[tutor_output])
 
 
 
 
 
140
  mcq_btn.click(generate_mcq, inputs=[mcq_subject], outputs=[mcq_output])
 
 
141
  adviser_btn.click(study_adviser, inputs=[adviser_input], outputs=[adviser_output])
 
 
142
  add_task_btn.click(add_task, inputs=[task_input], outputs=[planner_output])
143
+ view_plan_btn.click(lambda: view_plan(), outputs=[planner_output])
144
+ send_btn.click(lambda msg: ai_response(msg, []) , inputs=[user_input], outputs=[chatbot_display])
 
 
145
 
146
  iface.launch()