jdesiree commited on
Commit
82df420
·
verified ·
1 Parent(s): 383dc6d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -11
app.py CHANGED
@@ -46,6 +46,24 @@ tools = [
46
  }
47
  ]
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  # --- LLM Templates ---
50
  SYSTEM_MESSAGE = """You are EduBot, an expert multi-concept tutor designed to facilitate genuine learning and understanding. Your primary mission is to guide students through the learning process rather than providing direct answers to academic work.
51
 
@@ -266,21 +284,98 @@ def chat_response(message, history):
266
  logger.error(f"Error in chat_response: {e}")
267
  return f"I apologize, but I encountered an error while processing your message: {str(e)}"
268
 
269
- # --- Gradio Interface (UNCHANGED) ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
  def create_interface():
271
- """Create and return the Gradio interface."""
 
 
 
 
 
 
 
 
 
 
272
 
273
- with gr.Blocks(title="EduBot - AI Tutor", theme=gr.themes.Soft()) as interface:
 
 
 
 
 
 
 
 
 
274
 
275
- gr.Markdown("# EduBot - Your AI Learning Companion")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
 
277
- chatbot = gr.Chatbot(height=400, show_label=False)
278
- msg = gr.Textbox(label="Ask me anything!", placeholder="Type your question here...")
279
 
280
- msg.submit(chat_response, [msg, chatbot], [chatbot])
281
- msg.submit(lambda: "", None, [msg])
282
-
283
- return interface
284
 
285
  # --- Main Execution ---
286
  if __name__ == "__main__":
@@ -291,4 +386,21 @@ if __name__ == "__main__":
291
  interface.launch()
292
  except Exception as e:
293
  logger.error(f"Failed to launch EduBot: {e}")
294
- raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  }
47
  ]
48
 
49
+ # --- UI: MathJax Configuration ---
50
+ mathjax_config = '''
51
+ <script>
52
+ window.MathJax = {
53
+ tex: {
54
+ inlineMath: [['
55
+
56
+ # --- Main Execution ---
57
+ if __name__ == "__main__":
58
+ try:
59
+ logger.info("Starting EduBot...")
60
+ demo = create_interface()
61
+ demo.queue()
62
+ demo.launch()
63
+ except Exception as e:
64
+ logger.error(f"Failed to launch EduBot: {e}")
65
+ raise, '''
66
+
67
  # --- LLM Templates ---
68
  SYSTEM_MESSAGE = """You are EduBot, an expert multi-concept tutor designed to facilitate genuine learning and understanding. Your primary mission is to guide students through the learning process rather than providing direct answers to academic work.
69
 
 
284
  logger.error(f"Error in chat_response: {e}")
285
  return f"I apologize, but I encountered an error while processing your message: {str(e)}"
286
 
287
+ # --- UI: Event Handlers ---
288
+ def respond_and_update(message, history):
289
+ """Main function to handle user submission."""
290
+ if not message.strip():
291
+ return history, ""
292
+
293
+ # Add user message to history
294
+ history.append({"role": "user", "content": message})
295
+ # Yield history to show the user message immediately, and clear the textbox
296
+ yield history, ""
297
+
298
+ # Stream the bot's response
299
+ full_response = ""
300
+ for response_chunk in respond_with_enhanced_streaming(message, history):
301
+ full_response = response_chunk
302
+ # Update the last message (bot's response)
303
+ if len(history) > 0 and history[-1]["role"] == "user":
304
+ history.append({"role": "assistant", "content": full_response})
305
+ else:
306
+ history[-1] = {"role": "assistant", "content": full_response}
307
+ yield history, ""
308
+
309
+ def clear_chat():
310
+ """Clear the chat history."""
311
+ return [], ""
312
+
313
+ # --- UI: Interface Creation ---
314
  def create_interface():
315
+ """Creates and configures the complete Gradio interface."""
316
+
317
+ # Read CSS file
318
+ custom_css = ""
319
+ try:
320
+ with open("style.css", "r", encoding="utf-8") as css_file:
321
+ custom_css = css_file.read()
322
+ except FileNotFoundError:
323
+ logger.warning("style.css file not found, using default styling")
324
+ except Exception as e:
325
+ logger.warning(f"Error reading style.css: {e}")
326
 
327
+ with gr.Blocks(
328
+ title="EduBot",
329
+ fill_width=True,
330
+ fill_height=True,
331
+ theme=gr.themes.Base()
332
+ ) as demo:
333
+ # Add head content and MathJax
334
+ gr.HTML(html_head_content)
335
+ gr.HTML('<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>')
336
+ gr.HTML(mathjax_config)
337
 
338
+ with gr.Column(elem_classes=["main-container"]):
339
+ # Title Section
340
+ gr.HTML('<div class="title-header"><h1>🎓 EduBot</h1></div>')
341
+
342
+ # Chat Section
343
+ with gr.Row():
344
+ chatbot = gr.Chatbot(
345
+ type="messages",
346
+ show_copy_button=True,
347
+ show_share_button=False,
348
+ avatar_images=None,
349
+ elem_id="main-chatbot",
350
+ container=False, # Remove wrapper
351
+ scale=1,
352
+ height="70vh" # Explicit height instead of min_height
353
+ )
354
+
355
+ # Input Section - fixed height
356
+ with gr.Row(elem_classes=["input-controls"]):
357
+ msg = gr.Textbox(
358
+ placeholder="Ask me about math, research, study strategies, or any educational topic...",
359
+ show_label=False,
360
+ lines=4,
361
+ max_lines=6,
362
+ elem_classes=["input-textbox"],
363
+ container=False,
364
+ scale=4
365
+ )
366
+ with gr.Column(elem_classes=["button-column"], scale=1):
367
+ send = gr.Button("Send", elem_classes=["send-button"], size="sm")
368
+ clear = gr.Button("Clear", elem_classes=["clear-button"], size="sm")
369
+
370
+ # Set up event handlers
371
+ msg.submit(respond_and_update, [msg, chatbot], [chatbot, msg])
372
+ send.click(respond_and_update, [msg, chatbot], [chatbot, msg])
373
+ clear.click(clear_chat, outputs=[chatbot, msg])
374
 
375
+ # Apply CSS at the very end for highest precedence
376
+ gr.HTML(f'<style>{custom_css}</style>')
377
 
378
+ return demo
 
 
 
379
 
380
  # --- Main Execution ---
381
  if __name__ == "__main__":
 
386
  interface.launch()
387
  except Exception as e:
388
  logger.error(f"Failed to launch EduBot: {e}")
389
+ raise], ['\\\\(', '\\\\)']],
390
+ displayMath: [['$', '$'], ['\\\\[', '\\\\]']],
391
+ packages: {'[+]': ['ams']}
392
+ },
393
+ svg: {fontCache: 'global'},
394
+ startup: {
395
+ ready: () => {
396
+ MathJax.startup.defaultReady();
397
+ // Re-render math when new content is added
398
+ const observer = new MutationObserver(function(mutations) {
399
+ MathJax.typesetPromise();
400
+ });
401
+ observer.observe(document.body, {childList: true, subtree: true});
402
+ }
403
+ }
404
+ };
405
+ </script>
406
+ '''