Wfafa commited on
Commit
202ea3b
ยท
verified ยท
1 Parent(s): 6522d73

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -22
app.py CHANGED
@@ -3,7 +3,14 @@ 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/"
@@ -20,8 +27,7 @@ def search_web(query):
20
  except Exception as e:
21
  return f"Search error: {e}"
22
 
23
- # ๐Ÿง  Memory setup
24
- HF_TOKEN = os.getenv("HF_TOKEN")
25
  MEMORY_FILE = "memory.json"
26
 
27
  def load_memory():
@@ -36,12 +42,11 @@ def save_memory(memory):
36
 
37
  memory = load_memory()
38
 
39
- # ๐Ÿ’ฌ Chat function
40
  def chat_with_model(message, history, context, file_input=None):
41
  if not isinstance(history, list):
42
  history = []
43
 
44
- # ๐ŸŒ Web search mode
45
  if message.lower().startswith("search "):
46
  query = message[7:]
47
  search_result = search_web(query)
@@ -49,12 +54,10 @@ def chat_with_model(message, history, context, file_input=None):
49
  save_memory(history)
50
  return history, history
51
 
52
- # ๐Ÿ“‚ If file is uploaded
53
  if file_input:
54
  file_name = file_input.name
55
  message += f"\n\n๐Ÿ“Ž (User uploaded a file named '{file_name}')"
56
 
57
- # ๐Ÿง  Build conversation
58
  conversation = [
59
  {"role": "system", "content": (
60
  "You are EduAI, a multilingual educational AI assistant created by a Sri Lankan student named Wafa Fazly. "
@@ -70,8 +73,8 @@ def chat_with_model(message, history, context, file_input=None):
70
 
71
  conversation.append({"role": "user", "content": message})
72
 
73
- # ๐Ÿš€ Send to Hugging Face model
74
  try:
 
75
  response = requests.post(
76
  "https://router.huggingface.co/v1/chat/completions",
77
  headers={
@@ -83,24 +86,26 @@ def chat_with_model(message, history, context, file_input=None):
83
  "messages": conversation
84
  }
85
  )
 
 
 
86
  data = response.json()
87
  reply = data["choices"][0]["message"]["content"]
88
 
89
- # ๐Ÿงฎ Clean up math formatting
90
- reply = reply.replace("Step", "\n\n**Step")
91
- reply = reply.replace(":", ":**")
92
- reply = reply.replace("\\[", "\n\n\\[")
93
- reply = reply.replace("\\]", "\\]\n\n")
94
 
95
  history.append((message, reply))
96
  save_memory(history)
97
  return history, history
98
 
99
  except Exception as e:
100
- print("Error:", e)
101
- history.append((message, "๐Ÿ˜… EduAI is having trouble connecting right now. Please try again later!"))
 
102
  return history, history
103
 
 
 
104
  # ๐Ÿ“˜ Sidebar context update
105
  def update_context(choice):
106
  if not choice:
@@ -113,7 +118,7 @@ def clear_memory():
113
  os.remove(MEMORY_FILE)
114
  return [], "๐Ÿงน Chat memory cleared! Start fresh."
115
 
116
- # ๐Ÿ–Œ Custom CSS for dark theme without green, using blue accents, file uploader as symbol in text area, no send button
117
  custom_css = """
118
  @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;600&display=swap');
119
 
@@ -265,12 +270,11 @@ body {
265
  }
266
  """
267
 
268
- # ๐ŸŽจ Gradio Interface with dark theme (blue accents, no green), file uploader as symbol, send on Enter (no send button)
269
- with gr.Blocks(theme=gr.themes.Base(), css=custom_css) as iface: # Using Base theme for full custom control
270
  gr.Markdown("# ๐ŸŽ“ **EduAI โ€” Your Professional Study Companion**", elem_classes="header-title")
271
 
272
  with gr.Row():
273
- # Sidebar
274
  with gr.Column(scale=1, min_width=250, elem_classes="sidebar"):
275
  gr.Markdown("### ๐Ÿงญ **Main Menu**", elem_classes="menu-title")
276
 
@@ -304,7 +308,6 @@ with gr.Blocks(theme=gr.themes.Base(), css=custom_css) as iface: # Using Base t
304
  Helps learners understand **Science, ICT, English, and more** in a simple, friendly way! ๐Ÿ’ฌ
305
  """, elem_classes="about-text")
306
 
307
- # Main Chat Area
308
  with gr.Column(scale=4, elem_classes="main-chat"):
309
  context_display = gr.Markdown(
310
  "๐Ÿ“˜ **You are in General Mode.** Ask EduAI anything about your studies!",
@@ -323,11 +326,10 @@ with gr.Blocks(theme=gr.themes.Base(), css=custom_css) as iface: # Using Base t
323
  msg = gr.Textbox(label="Ask EduAI:", placeholder="Type your question here...", elem_classes="chat-input", show_label=False)
324
  file_input = gr.File(label="๐Ÿ“Ž", file_types=[".pdf", ".docx", ".png", ".jpg"], elem_classes="file-upload", show_label=False)
325
 
326
- # Event Handlers
327
  subj.change(update_context, inputs=subj, outputs=context_display)
328
  planner.change(update_context, inputs=planner, outputs=context_display)
329
  lang.change(update_context, inputs=lang, outputs=context_display)
330
- msg.submit(chat_with_model, inputs=[msg, chatbot, context_display, file_input], outputs=[chatbot, chatbot]) # Send on Enter
331
  clear_btn.click(clear_memory, outputs=[chatbot, context_display])
332
 
333
  iface.launch()
 
3
  import requests
4
  import json
5
 
6
+ # Test HF_TOKEN
7
+ HF_TOKEN = os.getenv("HF_TOKEN")
8
+ if not HF_TOKEN:
9
+ print("Error: HF_TOKEN not set. Please set your Hugging Face API token.")
10
+ else:
11
+ print("HF_TOKEN loaded successfully.")
12
+
13
+ # ๐ŸŒ Web search function (unchanged)
14
  def search_web(query):
15
  try:
16
  url = "https://api.duckduckgo.com/"
 
27
  except Exception as e:
28
  return f"Search error: {e}"
29
 
30
+ # ๐Ÿง  Memory setup (unchanged)
 
31
  MEMORY_FILE = "memory.json"
32
 
33
  def load_memory():
 
42
 
43
  memory = load_memory()
44
 
45
+ # ๐Ÿ’ฌ Chat function with better error handling
46
  def chat_with_model(message, history, context, file_input=None):
47
  if not isinstance(history, list):
48
  history = []
49
 
 
50
  if message.lower().startswith("search "):
51
  query = message[7:]
52
  search_result = search_web(query)
 
54
  save_memory(history)
55
  return history, history
56
 
 
57
  if file_input:
58
  file_name = file_input.name
59
  message += f"\n\n๐Ÿ“Ž (User uploaded a file named '{file_name}')"
60
 
 
61
  conversation = [
62
  {"role": "system", "content": (
63
  "You are EduAI, a multilingual educational AI assistant created by a Sri Lankan student named Wafa Fazly. "
 
73
 
74
  conversation.append({"role": "user", "content": message})
75
 
 
76
  try:
77
+ # Primary API call
78
  response = requests.post(
79
  "https://router.huggingface.co/v1/chat/completions",
80
  headers={
 
86
  "messages": conversation
87
  }
88
  )
89
+ if response.status_code != 200:
90
+ raise Exception(f"API Error: {response.status_code} - {response.text}")
91
+
92
  data = response.json()
93
  reply = data["choices"][0]["message"]["content"]
94
 
95
+ reply = reply.replace("Step", "\n\n**Step").replace(":", ":**").replace("\\[", "\n\n\\[").replace("\\]", "\\]\n\n")
 
 
 
 
96
 
97
  history.append((message, reply))
98
  save_memory(history)
99
  return history, history
100
 
101
  except Exception as e:
102
+ print("Backend Error:", e)
103
+ error_msg = "๐Ÿ˜… EduAI is having trouble connecting right now. Check your HF_TOKEN or try again later!"
104
+ history.append((message, error_msg))
105
  return history, history
106
 
107
+ # Rest of the code (unchanged, including UI and CSS)
108
+
109
  # ๐Ÿ“˜ Sidebar context update
110
  def update_context(choice):
111
  if not choice:
 
118
  os.remove(MEMORY_FILE)
119
  return [], "๐Ÿงน Chat memory cleared! Start fresh."
120
 
121
+ # ๐Ÿ–Œ Custom CSS (unchanged)
122
  custom_css = """
123
  @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;600&display=swap');
124
 
 
270
  }
271
  """
272
 
273
+ # ๐ŸŽจ Gradio Interface (unchanged)
274
+ with gr.Blocks(theme=gr.themes.Base(), css=custom_css) as iface:
275
  gr.Markdown("# ๐ŸŽ“ **EduAI โ€” Your Professional Study Companion**", elem_classes="header-title")
276
 
277
  with gr.Row():
 
278
  with gr.Column(scale=1, min_width=250, elem_classes="sidebar"):
279
  gr.Markdown("### ๐Ÿงญ **Main Menu**", elem_classes="menu-title")
280
 
 
308
  Helps learners understand **Science, ICT, English, and more** in a simple, friendly way! ๐Ÿ’ฌ
309
  """, elem_classes="about-text")
310
 
 
311
  with gr.Column(scale=4, elem_classes="main-chat"):
312
  context_display = gr.Markdown(
313
  "๐Ÿ“˜ **You are in General Mode.** Ask EduAI anything about your studies!",
 
326
  msg = gr.Textbox(label="Ask EduAI:", placeholder="Type your question here...", elem_classes="chat-input", show_label=False)
327
  file_input = gr.File(label="๐Ÿ“Ž", file_types=[".pdf", ".docx", ".png", ".jpg"], elem_classes="file-upload", show_label=False)
328
 
 
329
  subj.change(update_context, inputs=subj, outputs=context_display)
330
  planner.change(update_context, inputs=planner, outputs=context_display)
331
  lang.change(update_context, inputs=lang, outputs=context_display)
332
+ msg.submit(chat_with_model, inputs=[msg, chatbot, context_display, file_input], outputs=[chatbot, chatbot])
333
  clear_btn.click(clear_memory, outputs=[chatbot, context_display])
334
 
335
  iface.launch()