Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,7 +3,14 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import json
|
| 5 |
|
| 6 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 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 |
-
|
|
|
|
| 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
|
| 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
|
| 269 |
-
with gr.Blocks(theme=gr.themes.Base(), css=custom_css) as iface:
|
| 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])
|
| 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()
|