Wfafa commited on
Commit
dc19466
·
verified ·
1 Parent(s): fa9fe00

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -67
app.py CHANGED
@@ -1,79 +1,71 @@
1
- import os
2
- import gradio as gr
3
- import requests
4
- import json
 
 
 
 
 
 
5
 
6
- HF_TOKEN = os.getenv("HF_TOKEN")
7
- MEMORY_FILE = "memory.json"
8
 
9
  # ----------------
10
- # Web search
11
  # ----------------
12
- def search_web(query):
13
- try:
14
- url = "https://api.duckduckgo.com/"
15
- params = {"q": query, "format": "json", "no_html": 1, "skip_disambig": 1}
16
- response = requests.get(url, params=params)
17
- data = response.json()
18
- if data.get("AbstractText"):
19
- return data["AbstractText"]
20
- elif data.get("RelatedTopics"):
21
- topics = [t.get("Text", "") for t in data["RelatedTopics"] if "Text" in t]
22
- return " ".join(topics[:3])
23
- else:
24
- return "No useful information found."
25
- except Exception as e:
26
- return f"Search error: {e}"
27
 
28
  # ----------------
29
- # Memory
30
  # ----------------
31
- def load_memory():
32
- if os.path.exists(MEMORY_FILE):
33
- with open(MEMORY_FILE, "r") as f:
34
- return json.load(f)
35
- return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- def save_memory(memory):
38
- with open(MEMORY_FILE, "w") as f:
39
- json.dump(memory, f)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- memory = load_memory()
42
 
43
  # ----------------
44
- # Chat function
45
  # ----------------
46
- def chat_with_model(message, history, context):
47
- if not isinstance(history, list):
48
- history = []
49
-
50
- if message.lower().startswith("search "):
51
- query = message[7:]
52
- result = search_web(query)
53
- history.append({"role": "user", "content": message})
54
- history.append({"role": "assistant", "content": f"🔎 {result}"})
55
- save_memory(history)
56
- return history, history
57
-
58
- conversation = [
59
- {"role": "system", "content": (
60
- "You are EduAI, a multilingual educational AI assistant created by a Sri Lankan student named Wafa Fazly. "
61
- "Explain clearly, step-by-step, with Markdown and LaTeX for math."
62
- )}
63
- ]
64
-
65
- for msg_obj in history[-5:]:
66
- conversation.append(msg_obj)
67
-
68
- conversation.append({"role": "user", "content": message})
69
-
70
- try:
71
- response = requests.post(
72
- "https://router.huggingface.co/v1/chat/completions",
73
- headers={"Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json"},
74
- json={"model": "deepseek-ai/DeepSeek-V3.2-Exp:novita", "messages": conversation}
75
- )
76
- data = response.json()
77
- reply = data["choices"][0]["message"]["content"]
78
-
79
- reply = reply.replace("Step
 
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()