Wfafa commited on
Commit
9b284e5
ยท
verified ยท
1 Parent(s): 235e024

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -79
app.py CHANGED
@@ -3,108 +3,183 @@ import gradio as gr
3
  import requests
4
  import json
5
 
6
- # ๐Ÿง  Hugging Face API Key (must be set in your HF Space secrets)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  HF_TOKEN = os.getenv("HF_TOKEN")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- # ๐ŸŒ Function to chat with model
10
- def chat_with_model(message, history):
11
- if not message:
12
- return history
13
-
14
- # prepare conversation
15
- messages = [
16
- {"role": "system", "content": (
17
- "You are EduAI โ€” an educational AI assistant created by Wafa Fazly "
18
- "from Fathima Muslim Ladies College. "
19
- "You help students learn subjects such as Math, Science, English, and IT. "
20
- "EduAI runs on the model 'Qwen/Qwen3-VL-8B-Instruct', which was originally "
21
- "trained by Alibaba. Always answer truthfully when asked about your creation."
22
- )}
23
- ]
24
-
25
- # Add chat history
26
- for msg in history[-5:]:
27
- messages.append(msg)
28
-
29
- messages.append({"role": "user", "content": message})
30
-
31
- # Send request to HF Inference endpoint
32
  try:
33
  response = requests.post(
34
  "https://router.huggingface.co/v1/chat/completions",
35
  headers={
36
  "Authorization": f"Bearer {HF_TOKEN}",
37
- "Content-Type": "application/json",
38
  },
39
  json={
40
  "model": "Qwen/Qwen3-VL-8B-Instruct:novita",
41
- "messages": messages
42
- },
43
- timeout=60
44
  )
45
 
46
  data = response.json()
47
  reply = data["choices"][0]["message"]["content"]
48
 
49
- history.append({"role": "user", "content": message})
50
- history.append({"role": "assistant", "content": reply})
51
- return history
52
-
53
- except Exception as e:
54
- history.append({"role": "assistant", "content": f"โš ๏ธ Connection error: {e}"})
55
- return history
56
-
57
-
58
- # ๐Ÿ“Ž File Upload Function
59
- def handle_file(file, history):
60
- if file is None:
61
- return history + [{"role": "assistant", "content": "โŒ No file uploaded."}]
62
- filename = file.name.split("/")[-1]
63
- history.append({"role": "assistant", "content": f"๐Ÿ“ File '{filename}' uploaded successfully!"})
64
- return history
65
 
 
 
66
 
67
- # โธ Pause Chat Function
68
- def pause_chat(history):
69
- history.append({"role": "assistant", "content": "โธ๏ธ Chat paused. You can continue anytime!"})
70
- return history
71
 
72
-
73
- # ๐Ÿง  Build Gradio Interface
74
- with gr.Blocks(title="EduAI โ€” Smart Study Assistant", theme=gr.themes.Soft(primary_hue="violet")) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  gr.Markdown(
76
  """
77
  # ๐ŸŽ“ **EduAI โ€” Your Smart Study Companion**
78
  Welcome to **EduAI**, your friendly study assistant! ๐Ÿ’ฌ
79
- Ask questions, upload files using ๐Ÿ“Ž, or pause with โธ anytime!
80
  """
81
  )
82
 
83
- chatbot = gr.Chatbot(label="EduAI Chat", type="messages", height=450)
84
-
85
  with gr.Row():
86
- upload_file = gr.File(visible=False, file_count="single", type="filepath")
87
-
88
- upload_icon = gr.Button("๐Ÿ“Ž", scale=0, elem_id="upload_icon")
89
- msg = gr.Textbox(placeholder="Type your question here...", scale=6)
90
- send = gr.Button("โœจ Send", scale=1)
91
- pause = gr.Button("โธ Pause", scale=1)
92
-
93
- # ๐Ÿ”— Actions
94
- send.click(chat_with_model, inputs=[msg, chatbot], outputs=chatbot)
95
- upload_file.upload(handle_file, inputs=[upload_file, chatbot], outputs=chatbot)
96
- pause.click(pause_chat, inputs=chatbot, outputs=chatbot)
97
-
98
- # ๐Ÿ“Ž JavaScript link for the symbol to trigger upload
99
- gr.HTML(
100
- """
101
- <script>
102
- const btn = document.querySelector('#upload_icon');
103
- const input = document.querySelector('input[type=file]');
104
- btn.addEventListener('click', () => input.click());
105
- </script>
106
- """
107
- )
108
-
109
- # ๐Ÿš€ Launch app
110
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ if message.lower().startswith("search "):
46
+ query = message[7:]
47
+ search_result = search_web(query)
48
+ history.append((message, f"๐Ÿ”Ž Here's what I found online:\n\n{search_result}"))
49
+ save_memory(history)
50
+ return history, history
51
+
52
+ conversation = [{"role": "system", "content": (
53
+ "You are EduAI โ€” an educational AI assistant created by Wafa Fazly "
54
+ "from Fathima Muslim Ladies College. "
55
+ "You help students learn subjects such as Math, Science, English, and IT. "
56
+ "EduAI runs on the model 'Qwen/Qwen3-VL-8B-Instruct', which was originally "
57
+ "trained by Alibaba. Always answer truthfully when asked about your creation."
58
+ )}]
59
+
60
+ for past_user, past_bot in history[-5:]:
61
+ conversation.append({"role": "user", "content": past_user})
62
+ conversation.append({"role": "assistant", "content": past_bot})
63
+
64
+ conversation.append({"role": "user", "content": message})
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  try:
67
  response = requests.post(
68
  "https://router.huggingface.co/v1/chat/completions",
69
  headers={
70
  "Authorization": f"Bearer {HF_TOKEN}",
71
+ "Content-Type": "application/json"
72
  },
73
  json={
74
  "model": "Qwen/Qwen3-VL-8B-Instruct:novita",
75
+ "messages": conversation
76
+ }
 
77
  )
78
 
79
  data = response.json()
80
  reply = data["choices"][0]["message"]["content"]
81
 
82
+ reply = reply.replace("Step", "\n\n**Step")
83
+ reply = reply.replace(":", ":**")
84
+ reply = reply.replace("\\[", "\n\n\\[")
85
+ reply = reply.replace("\\]", "\\]\n\n")
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
+ if "\\" in reply or "log_" in reply or "^" in reply:
88
+ reply = f"{reply}"
89
 
90
+ history.append((message, reply))
91
+ save_memory(history)
92
+ return history, history
 
93
 
94
+ except Exception as e:
95
+ print("Error:", e)
96
+ history.append((message, "๐Ÿ˜… EduAI is having trouble connecting right now. Please try again later!"))
97
+ return history, history
98
+
99
+ # ๐Ÿ“˜ Sidebar context update
100
+ def update_context(choice):
101
+ if not choice:
102
+ return "๐Ÿ“˜ **You are in General Mode.** Ask EduAI anything about your studies!"
103
+ return f"๐Ÿ“˜ **You selected {choice} mode.** Ask anything related to this topic!"
104
+
105
+ # ๐Ÿงน Clear chat memory
106
+ def clear_memory():
107
+ if os.path.exists(MEMORY_FILE):
108
+ os.remove(MEMORY_FILE)
109
+ return [], "๐Ÿงน Chat memory cleared! Start fresh."
110
+
111
+ # ๐ŸŽจ Gradio Interface (UI Improved)
112
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="violet")) as iface:
113
  gr.Markdown(
114
  """
115
  # ๐ŸŽ“ **EduAI โ€” Your Smart Study Companion**
116
  Welcome to **EduAI**, your friendly study assistant! ๐Ÿ’ฌ
117
+ Get help in **Science, ICT, English, Mathematics**, and more.
118
  """
119
  )
120
 
 
 
121
  with gr.Row():
122
+ with gr.Column(scale=1, min_width=230):
123
+ gr.Markdown("### ๐Ÿงญ **Main Menu**")
124
+
125
+ with gr.Accordion("๐Ÿ“š Subject Tutor", open=False):
126
+ subj = gr.Radio(
127
+ ["Science ๐Ÿงช", "ICT ๐Ÿ’ป", "English ๐Ÿ“˜", "Mathematics โž—"],
128
+ label="Choose a subject"
129
+ )
130
+
131
+ with gr.Accordion("๐Ÿ—“ Study Planner", open=False):
132
+ planner = gr.Radio(
133
+ ["View Plan ๐Ÿ“…", "Add Task โœ๏ธ", "Study Tips ๐Ÿ’ก"],
134
+ label="Planner Options"
135
+ )
136
+
137
+ with gr.Accordion("๐ŸŒ Languages", open=False):
138
+ lang = gr.Radio(
139
+ ["Learn Sinhala ๐Ÿ‡ฑ๐Ÿ‡ฐ", "Learn Tamil ๐Ÿ‡ฎ๐Ÿ‡ณ", "Learn English ๐Ÿ‡ฌ๐Ÿ‡ง", "Learn Spanish ๐Ÿ‡ช๐Ÿ‡ธ"],
140
+ label="Language Options"
141
+ )
142
+
143
+ with gr.Accordion("โš™๏ธ Settings", open=False):
144
+ clear_btn = gr.Button("๐Ÿงน Clear Memory")
145
+
146
+ with gr.Accordion("๐Ÿ‘ฉโ€๐ŸŽ“ About", open=False):
147
+ gr.Markdown(
148
+ """
149
+ EduAI was designed and fine-tuned by **Wafa Fazly**,
150
+ a passionate Sri Lankan student ๐Ÿ‘ฉโ€๐Ÿ’ป
151
+ to help learners explore **Science, ICT, English, and more** โ€”
152
+ in a smart and friendly way! ๐ŸŒŸ
153
+ """
154
+ )
155
+
156
+ with gr.Column(scale=4):
157
+ context_display = gr.Markdown("๐Ÿ“˜ **You are in General Mode.** Ask EduAI anything about your studies!")
158
+ chatbot = gr.Chatbot(
159
+ label="๐Ÿ’ฌ EduAI Chat Window",
160
+ height=450,
161
+ render_markdown=True,
162
+ bubble_full_width=False,
163
+ latex_delimiters=[
164
+ {"left": "$$", "right": "$$", "display": True},
165
+ {"left": "\\[", "right": "\\]", "display": True}
166
+ ]
167
+ )
168
+
169
+ msg = gr.Textbox(
170
+ label="๐Ÿ’ญ Type your question here...",
171
+ placeholder="Ask EduAI anything about your studies..."
172
+ )
173
+
174
+ with gr.Row():
175
+ send = gr.Button("โœจ Send Message")
176
+ pause = gr.Button("โธ Pause", variant="secondary")
177
+
178
+ # ๐Ÿช„ Event handlers
179
+ subj.change(update_context, inputs=subj, outputs=context_display)
180
+ planner.change(update_context, inputs=planner, outputs=context_display)
181
+ lang.change(update_context, inputs=lang, outputs=context_display)
182
+ send.click(chat_with_model, inputs=[msg, chatbot, context_display], outputs=[chatbot, chatbot])
183
+ clear_btn.click(clear_memory, outputs=[chatbot, context_display])
184
+
185
+ iface.launch()