Wfafa commited on
Commit
577009b
Β·
verified Β·
1 Parent(s): baacc26

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -167
app.py CHANGED
@@ -1,184 +1,72 @@
1
- import os
2
  import gradio as gr
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({"role": "user", "content": message})
49
- history.append({"role": "assistant", "content": f"πŸ”Ž Here's what I found online:\n\n{search_result}"})
50
- save_memory(history)
51
- return history, history
52
-
53
- # System role
54
- conversation = [{"role": "system", "content": (
55
- "You are EduAI β€” an educational AI assistant created by Wafa Fazly "
56
- "from Fathima Muslim Ladies College. "
57
- "You help students learn subjects such as Math, Science, English, and IT. "
58
- "EduAI runs on the model 'Qwen/Qwen3-VL-8B-Instruct', trained by Alibaba. "
59
- "Always answer truthfully when asked about your creation."
60
- )}]
61
-
62
- for msg in history[-5:]:
63
- conversation.append(msg)
64
-
65
- conversation.append({"role": "user", "content": message})
66
-
67
- # πŸš€ Send to Hugging Face
68
- try:
69
- response = requests.post(
70
- "https://router.huggingface.co/v1/chat/completions",
71
- headers={
72
- "Authorization": f"Bearer {HF_TOKEN}",
73
- "Content-Type": "application/json"
74
- },
75
- json={
76
- "model": "Qwen/Qwen3-VL-8B-Instruct:novita",
77
- "messages": conversation
78
- }
79
- )
80
- data = response.json()
81
- reply = data["choices"][0]["message"]["content"]
82
- history.append({"role": "user", "content": message})
83
- history.append({"role": "assistant", "content": reply})
84
- save_memory(history)
85
- return history, history
86
- except Exception as e:
87
- history.append({"role": "assistant", "content": f"πŸ˜… EduAI error: {e}"})
88
- return history, history
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
- # πŸ“Ž Handle File Uploads
92
  def handle_file(file, history):
93
  if file is None:
94
- history.append({"role": "assistant", "content": "⚠️ No file uploaded yet."})
95
- return history
96
  filename = file.name.split("/")[-1]
97
- history.append({"role": "assistant", "content": f"πŸ“ File uploaded: **{filename}**\nβœ… Received successfully!"})
98
  return history
99
 
100
- # ⏸ Pause Chat
101
  def pause_chat(history):
102
- history.append({"role": "assistant", "content": "⏸️ Chat paused. Click 'Send' to continue."})
103
  return history
104
 
105
- # 🎨 Interface
106
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="violet")) as iface:
107
- gr.Markdown("# πŸŽ“ **EduAI β€” Your Smart Study Companion**")
108
-
109
- with gr.Row():
110
- with gr.Column(scale=1, min_width=230):
111
- gr.Markdown("### 🧭 **Main Menu**")
112
-
113
- with gr.Accordion("πŸ“š Subject Tutor", open=False):
114
- subj = gr.Radio(
115
- ["Science οΏ½οΏ½", "ICT πŸ’»", "English πŸ“˜", "Mathematics βž—"],
116
- label="Choose a subject"
117
- )
118
-
119
- with gr.Accordion("βš™οΈ Settings", open=False):
120
- clear_btn = gr.Button("🧹 Clear Memory")
121
 
122
- with gr.Column(scale=4):
123
- context_display = gr.Markdown("πŸ“˜ **You are in General Mode.** Ask EduAI anything about your studies!")
 
 
124
 
125
- chatbot = gr.Chatbot(
126
- label="πŸ’¬ EduAI Chat Window",
127
- height=450,
128
- type="messages"
129
- )
130
 
131
- with gr.Row():
132
- # 🧷 Tiny file upload icon (like ChatGPT)
133
- upload_file = gr.File(
134
- scale=1,
135
- file_count="single",
136
- type="filepath",
137
- elem_classes=["icon-upload"]
138
- )
139
-
140
- msg = gr.Textbox(
141
- placeholder="Ask EduAI anything...",
142
- scale=6
143
- )
144
 
145
- send = gr.Button("✨", scale=1)
146
- pause_btn = gr.Button("⏸", scale=1)
 
 
 
 
 
 
147
 
148
- # 🌟 Events
149
- subj.change(lambda s: f"πŸ“˜ You selected {s} mode.", inputs=subj, outputs=context_display)
150
- send.click(chat_with_model, inputs=[msg, chatbot, context_display], outputs=[chatbot, chatbot])
151
- clear_btn.click(lambda: ([], "🧹 Chat memory cleared!"), outputs=[chatbot, context_display])
152
  upload_file.upload(handle_file, inputs=[upload_file, chatbot], outputs=chatbot)
153
- pause_btn.click(pause_chat, inputs=chatbot, outputs=chatbot)
154
-
155
- # πŸ’… Add custom CSS for icon style
156
- iface.load(
157
- None,
158
- None,
159
- None,
160
- _js="""
161
- () => {
162
- const upload = document.querySelector('.icon-upload input');
163
- const parent = document.querySelector('.icon-upload');
164
- if (upload && parent) {
165
- parent.style.border = 'none';
166
- parent.style.background = 'none';
167
- parent.style.width = '32px';
168
- parent.style.height = '32px';
169
- parent.style.cursor = 'pointer';
170
- parent.style.display = 'flex';
171
- parent.style.alignItems = 'center';
172
- parent.style.justifyContent = 'center';
173
- const icon = document.createElement('span');
174
- icon.textContent = 'πŸ“Ž';
175
- icon.style.fontSize = '22px';
176
- icon.style.cursor = 'pointer';
177
- parent.appendChild(icon);
178
- icon.onclick = () => upload.click();
179
- }
180
- }
181
- """
182
- )
183
-
184
- iface.launch()
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ # 🌟 Chatbot response logic
4
+ def eduai_chat(message, history):
5
+ if not message:
6
+ return history
7
+ if message.lower() == "hello":
8
+ response = "πŸ‘‹ Hi there! I'm EduAI, your smart study assistant!"
9
+ elif "chemistry" in message.lower():
10
+ response = "βš—οΈ Chemistry is fascinating! Would you like to learn about elements or reactions?"
11
+ elif "physics" in message.lower():
12
+ response = "βš›οΈ Physics explains the universe! Want to discuss motion, energy, or quantum concepts?"
13
+ else:
14
+ response = "I'm still learning! 😊 Could you rephrase or ask another question?"
15
+
16
+ history.append({"role": "user", "content": message})
17
+ history.append({"role": "assistant", "content": response})
18
+ return history
19
 
20
+ # πŸ“Ž Handle file uploads
21
  def handle_file(file, history):
22
  if file is None:
23
+ return history + [{"role": "assistant", "content": "❌ No file uploaded."}]
 
24
  filename = file.name.split("/")[-1]
25
+ history.append({"role": "assistant", "content": f"πŸ“ File '{filename}' received successfully!"})
26
  return history
27
 
28
+ # ⏸ Pause chat
29
  def pause_chat(history):
30
+ history.append({"role": "assistant", "content": "⏸️ Chat paused. You can continue anytime!"})
31
  return history
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
+ # 🌸 Build Interface
35
+ with gr.Blocks(title="EduAI - Your Smart Study Assistant") as demo:
36
+ gr.Markdown("## 🧠 **EduAI – Your Smart Study Assistant**")
37
+ gr.Markdown("Ask questions, upload files with πŸ“Ž, or pause with ⏸ anytime!")
38
 
39
+ chatbot = gr.Chatbot(label="EduAI", type="messages", height=400)
 
 
 
 
40
 
41
+ with gr.Row():
42
+ # hidden uploader
43
+ upload_file = gr.File(
44
+ visible=False, # hidden but functional
45
+ file_count="single",
46
+ type="filepath"
47
+ )
 
 
 
 
 
 
48
 
49
+ # file icon button
50
+ upload_icon = gr.Button("πŸ“Ž", scale=0, elem_id="upload_icon")
51
+ msg = gr.Textbox(
52
+ placeholder="Type your message here...",
53
+ scale=6
54
+ )
55
+ send = gr.Button("✨ Send", scale=1)
56
+ pause = gr.Button("⏸ Pause", scale=1)
57
 
58
+ # connect components
59
+ send.click(eduai_chat, inputs=[msg, chatbot], outputs=chatbot)
 
 
60
  upload_file.upload(handle_file, inputs=[upload_file, chatbot], outputs=chatbot)
61
+ pause.click(pause_chat, inputs=chatbot, outputs=chatbot)
62
+
63
+ # πŸͺ„ small JavaScript trick to trigger hidden uploader
64
+ gr.HTML("""
65
+ <script>
66
+ const btn = document.querySelector('#upload_icon');
67
+ const input = document.querySelector('input[type=file]');
68
+ btn.addEventListener('click', () => input.click());
69
+ </script>
70
+ """)
71
+
72
+ demo.launch()