Wfafa commited on
Commit
2e78e50
ยท
verified ยท
1 Parent(s): dc19466

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +174 -69
app.py CHANGED
@@ -1,71 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  reply = data["choices"][0]["message"]["content"]
2
- reply = reply.replace("Step", "โžก๏ธ Step") # Optional formatting
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  except Exception as e:
4
- reply = f"โš ๏ธ Error: {str(e)}"
5
-
6
- history.append({"role": "user", "content": message})
7
- history.append({"role": "assistant", "content": reply})
8
-
9
- save_memory(history)
10
- return history, history
11
-
12
-
13
- # ----------------
14
- # Greeting Function
15
- # ----------------
16
- def eduai_greeting():
17
- return [{"role": "assistant", "content": "๐Ÿ‘‹ Hey there! I'm **EduAI**, your smart study assistant. How can I help you today?"}]
18
-
19
-
20
- # ----------------
21
- # UI Components
22
- # ----------------
23
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo")) as demo:
24
- gr.Markdown(
25
- """
26
- <h1 style="text-align:center; color:#4C1D95;">โœจ EduAI โ€” Your Personal Study Assistant โœจ</h1>
27
- <p style="text-align:center;">Ask me about <b>Science, Math, IT, AI, or Languages</b> โ€” Iโ€™ll explain everything step-by-step!</p>
28
- """
29
- )
30
-
31
- chatbot = gr.Chatbot(
32
- label="EduAI Chat",
33
- height=450,
34
- bubble_full_width=False,
35
- avatar_images=("https://cdn-icons-png.flaticon.com/512/4712/4712104.png", None)
36
- )
37
-
38
- context_input = gr.Textbox(
39
- label="๐Ÿ”ง Context (Optional)",
40
- placeholder="Add custom instructions for EduAI (e.g., 'Explain like Iโ€™m 16 years old')",
41
- lines=2
42
- )
43
-
44
- msg = gr.Textbox(
45
- label="๐Ÿ’ฌ Type your question",
46
- placeholder="Ask me anything...",
47
- )
48
-
49
- clear_btn = gr.Button("๐Ÿงน Clear Chat", variant="secondary")
50
-
51
- # ----------------
52
- # Logic Connections
53
- # ----------------
54
- msg.submit(
55
- chat_with_model,
56
- [msg, chatbot, context_input],
57
- [chatbot, chatbot]
58
- )
59
-
60
- msg.submit(lambda: "", None, msg)
61
-
62
- clear_btn.click(lambda: ([], []), None, [chatbot, chatbot])
63
-
64
- demo.load(eduai_greeting, None, chatbot)
65
-
66
-
67
- # ----------------
68
- # Run App
69
- # ----------------
70
- if __name__ == "__main__":
71
- demo.launch()
 
 
 
 
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]) # just a few results
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, file_input=None):
42
+ if not isinstance(history, list):
43
+ history = []
44
+
45
+ # ๐ŸŒ Web search mode
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 is uploaded
54
+ if file_input:
55
+ file_name = file_input.name
56
+ message += f"\n\n๐Ÿ“Ž (User uploaded a file named '{file_name}')"
57
+
58
+ # ๐Ÿง  Build conversation
59
+ conversation = [
60
+ {"role": "system", "content": (
61
+ "You are EduAI, a multilingual educational AI assistant created by a Sri Lankan student named Wafa Fazly. "
62
+ "When solving math, explain step-by-step like a professional tutor. "
63
+ "Use Markdown and LaTeX formatting for equations (use \\[ and \\]). "
64
+ "Keep answers neat, structured, and student-friendly."
65
+ )}
66
+ ]
67
+
68
+ for past_user, past_bot in history[-5:]:
69
+ conversation.append({"role": "user", "content": past_user})
70
+ conversation.append({"role": "assistant", "content": past_bot})
71
+
72
+ conversation.append({"role": "user", "content": message})
73
+
74
+ # ๐Ÿš€ Send to Hugging Face model
75
+ try:
76
+ response = requests.post(
77
+ "https://router.huggingface.co/v1/chat/completions",
78
+ headers={
79
+ "Authorization": f"Bearer {HF_TOKEN}",
80
+ "Content-Type": "application/json"
81
+ },
82
+ json={
83
+ "model": "deepseek-ai/DeepSeek-V3.2-Exp:novita",
84
+ "messages": conversation
85
+ }
86
+ )
87
+
88
+ data = response.json()
89
  reply = data["choices"][0]["message"]["content"]
90
+
91
+ # ๐Ÿงฎ Clean up math formatting
92
+ reply = reply.replace("Step", "\n\n**Step")
93
+ reply = reply.replace(":", ":**")
94
+ reply = reply.replace("\\[", "\n\n\\[")
95
+ reply = reply.replace("\\]", "\\]\n\n")
96
+
97
+ # โœ… Add Markdown + LaTeX support
98
+ if "\\" in reply or "log_" in reply or "^" in reply:
99
+ reply = f"{reply}"
100
+
101
+ history.append((message, reply))
102
+ save_memory(history)
103
+ return history, history
104
+
105
  except Exception as e:
106
+ print("Error:", e)
107
+ history.append((message, "๐Ÿ˜… EduAI is having trouble connecting right now. Please try again later!"))
108
+ return history, history
109
+
110
+ # ๐Ÿ“˜ Sidebar context update
111
+ def update_context(choice):
112
+ if not choice:
113
+ return "๐Ÿ“˜ **You are in General Mode.** Ask EduAI anything about your studies!"
114
+ return f"๐Ÿ“˜ **You selected {choice} mode.** Ask anything related to this topic!"
115
+
116
+ # ๐Ÿงน Clear chat memory
117
+ def clear_memory():
118
+ if os.path.exists(MEMORY_FILE):
119
+ os.remove(MEMORY_FILE)
120
+ return [], "๐Ÿงน Chat memory cleared! Start fresh."
121
+
122
+ # ๐ŸŽจ Gradio Interface
123
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="violet")) as iface:
124
+ gr.Markdown("# ๐ŸŽ“ **EduAI โ€” Your Smart Study Companion**")
125
+
126
+ with gr.Row():
127
+ with gr.Column(scale=1, min_width=230):
128
+ gr.Markdown("### ๐Ÿงญ **Main Menu**")
129
+
130
+ with gr.Accordion("๐Ÿ“š Subject Tutor", open=False):
131
+ subj = gr.Radio(
132
+ ["Science ๐Ÿงช", "ICT ๐Ÿ’ป", "English ๐Ÿ“˜", "Mathematics โž—"],
133
+ label="Choose a subject"
134
+ )
135
+
136
+ with gr.Accordion("๐Ÿ—“ Study Planner", open=False):
137
+ planner = gr.Radio(
138
+ ["View Plan ๐Ÿ“…", "Add Task โœ๏ธ", "Study Tips ๐Ÿ’ก"],
139
+ label="Planner Options"
140
+ )
141
+
142
+ with gr.Accordion("๐ŸŒ Languages", open=False):
143
+ lang = gr.Radio(
144
+ ["Learn Sinhala ๐Ÿ‡ฑ๐Ÿ‡ฐ", "Learn Tamil ๐Ÿ‡ฎ๐Ÿ‡ณ", "Learn English ๐Ÿ‡ฌ๐Ÿ‡ง", "Learn Spanish ๐Ÿ‡ช๐Ÿ‡ธ"],
145
+ label="Language Options"
146
+ )
147
+
148
+ with gr.Accordion("โš™๏ธ Settings", open=False):
149
+ clear_btn = gr.Button("๐Ÿงน Clear Memory")
150
+
151
+ with gr.Accordion("๐Ÿ‘ฉโ€๐ŸŽ“ About", open=False):
152
+ gr.Markdown("""
153
+ EduAI โ€“ developed and fine-tuned by **Wafa Fazly** using a pre-trained AI model,
154
+ to help learners understand **Science, ICT, English, and more** โ€”
155
+ in a simple and friendly way! ๐Ÿ’ฌ
156
+ """)
157
+
158
+ with gr.Column(scale=4):
159
+ context_display = gr.Markdown("๐Ÿ“˜ **You are in General Mode.** Ask EduAI anything about your studies!")
160
+ chatbot = gr.Chatbot(
161
+ label="EduAI Chat",
162
+ height=450,
163
+ render_markdown=True,
164
+ latex_delimiters=[{"left": "$$", "right": "$$", "display": True}, {"left": "\\[", "right": "\\]", "display": True}]
165
+ )
166
+ msg = gr.Textbox(label="Ask EduAI:")
167
+ send = gr.Button("Send โœˆ๏ธ")
168
+
169
+ # ๐Ÿช„ Event handlers
170
+ subj.change(update_context, inputs=subj, outputs=context_display)
171
+ planner.change(update_context, inputs=planner, outputs=context_display)
172
+ lang.change(update_context, inputs=lang, outputs=context_display)
173
+ send.click(chat_with_model, inputs=[msg, chatbot, context_display, file_input], outputs=[chatbot, chatbot])
174
+ clear_btn.click(clear_memory, outputs=[chatbot, context_display])
175
+
176
+ iface.launch()