test / ui_components.py
Mahdi Naser Moghadasi
Refactor app.py into modular architecture
6cff14b
Raw History Blame Contribute Delete
19.9 kB
"""
UI components module for BrightMind AI
Contains Gradio interface components and styling
"""
import gradio as gr
from config import debug_token_status
from content_generators import (
generate_lesson_plan_with_progress,
generate_quiz_with_progress,
generate_content_with_progress
)
from email_service import submit_feedback
from database import get_feedback_stats, view_feedback_admin
from ai_services import generate_albert_response
def create_main_interface():
"""Create the main Gradio interface"""
# Debug token status
debug_token_status()
# Custom CSS for modern styling
custom_css = """
.modern-card {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 20px;
padding: 30px;
margin: 20px 0;
box-shadow: 0 10px 30px rgba(0,0,0,0.1);
color: white;
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.modern-card:hover {
transform: translateY(-5px);
box-shadow: 0 15px 40px rgba(0,0,0,0.2);
}
.slide-in-left {
animation: slideInLeft 0.6s ease-out;
}
.slide-in-right {
animation: slideInRight 0.6s ease-out;
}
@keyframes slideInLeft {
from { transform: translateX(-100px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
@keyframes slideInRight {
from { transform: translateX(100px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
.progress-container {
background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
border-radius: 15px;
padding: 20px;
margin: 20px 0;
text-align: center;
border: 2px solid #667eea;
}
.progress-bar {
width: 100%;
height: 8px;
background: #e9ecef;
border-radius: 4px;
overflow: hidden;
margin: 15px 0;
}
.progress-fill {
height: 100%;
background: linear-gradient(90deg, #667eea, #764ba2);
border-radius: 4px;
animation: progress 2s ease-in-out infinite;
}
@keyframes progress {
0% { width: 0%; }
50% { width: 70%; }
100% { width: 100%; }
}
.generation-status {
font-weight: 600;
color: #667eea;
margin: 10px 0;
font-size: 1.1rem;
}
.typewriter-container {
background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
border-radius: 15px;
padding: 20px;
margin: 20px 0;
border-left: 4px solid #667eea;
}
.typewriter-header {
display: flex;
align-items: center;
margin-bottom: 15px;
}
.book-icon {
font-size: 24px;
margin-right: 10px;
}
.typing-dots span {
animation: typing 1.4s infinite;
margin: 0 2px;
}
.typing-dots span:nth-child(2) { animation-delay: 0.2s; }
.typing-dots span:nth-child(3) { animation-delay: 0.4s; }
@keyframes typing {
0%, 60%, 100% { opacity: 0; }
30% { opacity: 1; }
}
"""
with gr.Blocks(css=custom_css, title="BrightMind AI - Educational Assistant") as interface:
# Header
gr.HTML("""
<div style="text-align: center; padding: 40px 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 20px; margin-bottom: 30px;">
<h1 style="font-size: 3rem; margin: 0; text-shadow: 2px 2px 4px rgba(0,0,0,0.3);">🧠 BrightMind AI</h1>
<p style="font-size: 1.3rem; margin: 10px 0; opacity: 0.9;">Your Intelligent Educational Assistant</p>
<p style="font-size: 1rem; margin: 0; opacity: 0.8;">Generate lesson plans, quizzes, and educational content with AI</p>
</div>
""")
# Main tabs
with gr.Tabs():
# Albert Chat Tab
with gr.TabItem("πŸ€– Albert Chat"):
create_albert_chat_tab()
# Lesson Plan Generator Tab
with gr.TabItem("πŸ“š Lesson Plan Generator"):
create_lesson_plan_tab()
# Quiz Generator Tab
with gr.TabItem("πŸ“ Quiz Generator"):
create_quiz_tab()
# Content Generator Tab
with gr.TabItem("πŸ“„ Content Generator"):
create_content_tab()
# Feedback Tab
with gr.TabItem("πŸ’¬ Feedback"):
create_feedback_tab()
# Admin Tab
with gr.TabItem("βš™οΈ Admin"):
create_admin_tab()
return interface
def create_albert_chat_tab():
"""Create the Albert chat interface"""
with gr.Row():
with gr.Column(scale=1):
gr.HTML("""
<div class="modern-card slide-in-left">
<h2 style="color: white; margin-bottom: 20px; font-size: 1.8rem;">πŸ€– Albert Chat</h2>
<p style="color: white; font-size: 1.1rem; margin-bottom: 20px;">Chat with Albert, your AI learning buddy!</p>
""")
user_name = gr.Textbox(
label="πŸ‘€ Your Name",
placeholder="Enter your name to start chatting",
value=""
)
user_age_group = gr.Dropdown(
choices=["Elementary (K-5)", "Middle School (6-8)", "High School (9-12)", "College", "Adult"],
label="πŸŽ“ Age Group",
value="Middle School (6-8)",
interactive=True
)
gr.HTML("</div>")
with gr.Column(scale=2):
gr.HTML("""
<div class="modern-card slide-in-right">
<h3 style="color: white; margin-bottom: 20px; font-size: 1.4rem;">πŸ’¬ Chat with Albert</h3>
""")
chat_display = gr.Chatbot(
label="",
height=400,
show_label=False,
container=True,
bubble_full_width=False
)
chat_input = gr.Textbox(
label="Type your message here...",
placeholder="Ask Albert anything about learning!",
lines=2
)
with gr.Row():
send_btn = gr.Button("Send", variant="primary")
clear_btn = gr.Button("Clear Chat", variant="secondary")
context_display = gr.HTML("", visible=False)
typing_indicator = gr.HTML("", visible=False)
gr.HTML("</div>")
# Event handlers
def send_message_with_typing(message, name, age_group, history):
"""Send message with typing effect"""
if not message.strip():
return history, "", "", ""
if history is None:
history = []
history.append([f"{name}: {message}", None])
# Generate Albert's response
albert_response = generate_albert_response(message, name, age_group, history)
history[-1][1] = albert_response
return history, "", "", ""
def clear_chat():
return [], "", "", ""
def initialize_chat(name, age_group):
if not name.strip():
return [], "", ""
welcome_message = f"Hi {name}! 🧠✨ I'm Albert, your learning buddy! What would you like to know about today? πŸ˜ŠπŸš€"
return [[None, welcome_message]], "", ""
# Connect event handlers
send_btn.click(
fn=send_message_with_typing,
inputs=[chat_input, user_name, user_age_group, chat_display],
outputs=[chat_display, chat_input, context_display, typing_indicator]
)
clear_btn.click(
fn=clear_chat,
outputs=[chat_display, context_display, context_display, typing_indicator]
)
user_name.change(
fn=initialize_chat,
inputs=[user_name, user_age_group],
outputs=[chat_display, context_display, context_display]
)
def create_lesson_plan_tab():
"""Create the lesson plan generator interface"""
with gr.Row():
with gr.Column():
gr.HTML("""
<div class="modern-card slide-in-left">
<h2 style="color: white; margin-bottom: 20px; font-size: 1.8rem;">πŸ“š Lesson Plan Generator</h2>
<p style="color: white; font-size: 1.1rem; margin-bottom: 20px;">Create comprehensive lesson plans with AI assistance</p>
""")
topic = gr.Textbox(label="πŸ“ Topic", placeholder="e.g., Photosynthesis, World War II, Algebra")
subject = gr.Dropdown(
choices=["Science", "Mathematics", "History", "English Language Arts", "Geography", "Art"],
label="πŸ“š Subject",
value="Science",
interactive=True
)
grade_level = gr.Dropdown(
choices=["K-2", "3-5", "6-8", "9-12"],
label="πŸŽ“ Grade Level",
value="6-8",
interactive=True
)
duration = gr.Slider(
minimum=30,
maximum=180,
step=15,
value=60,
label="⏱️ Duration (minutes)"
)
difficulty = gr.Dropdown(
choices=["Beginner", "Intermediate", "Advanced"],
label="🎯 Difficulty",
value="Intermediate",
interactive=True
)
generate_lesson_btn = gr.Button("πŸš€ Generate Lesson Plan", variant="primary")
gr.HTML("</div>")
with gr.Column():
gr.HTML("""
<div class="modern-card slide-in-right">
<h3 style="color: white; margin-bottom: 20px; font-size: 1.4rem;">πŸ“‹ Generated Lesson Plan</h3>
""")
progress_display = gr.HTML("", visible=False)
lesson_plan_output = gr.Markdown(label="")
gr.HTML("</div>")
# Event handler
generate_lesson_btn.click(
fn=generate_lesson_plan_with_progress,
inputs=[topic, subject, grade_level, duration, difficulty],
outputs=[progress_display, lesson_plan_output]
)
def create_quiz_tab():
"""Create the quiz generator interface"""
with gr.Row():
with gr.Column():
gr.HTML("""
<div class="modern-card slide-in-left">
<h2 style="color: white; margin-bottom: 20px; font-size: 1.8rem;">πŸ“ Quiz Generator</h2>
<p style="color: white; font-size: 1.1rem; margin-bottom: 20px;">Create engaging quizzes with AI assistance</p>
""")
quiz_topic = gr.Textbox(label="πŸ“ Topic", placeholder="e.g., Photosynthesis, World War II, Algebra")
quiz_subject = gr.Dropdown(
choices=["Science", "Mathematics", "History", "English Language Arts", "Geography", "Art"],
label="πŸ“š Subject",
value="Science",
interactive=True
)
quiz_grade_level = gr.Dropdown(
choices=["K-2", "3-5", "6-8", "9-12"],
label="πŸŽ“ Grade Level",
value="6-8",
interactive=True
)
question_count = gr.Slider(
minimum=3,
maximum=20,
step=1,
value=5,
label="❓ Number of Questions"
)
question_types = gr.CheckboxGroup(
choices=["Multiple Choice", "True/False", "Short Answer", "Fill in the Blank"],
label="πŸ“‹ Question Types",
value=["Multiple Choice", "True/False"]
)
generate_quiz_btn = gr.Button("πŸš€ Generate Quiz", variant="primary")
gr.HTML("</div>")
with gr.Column():
gr.HTML("""
<div class="modern-card slide-in-right">
<h3 style="color: white; margin-bottom: 20px; font-size: 1.4rem;">πŸ“ Generated Quiz</h3>
""")
quiz_progress_display = gr.HTML("", visible=False)
quiz_output = gr.Markdown(label="")
gr.HTML("</div>")
# Event handler
generate_quiz_btn.click(
fn=generate_quiz_with_progress,
inputs=[quiz_topic, quiz_subject, quiz_grade_level, question_count, question_types],
outputs=[quiz_progress_display, quiz_output]
)
def create_content_tab():
"""Create the content generator interface"""
with gr.Row():
with gr.Column():
gr.HTML("""
<div class="modern-card slide-in-left">
<h2 style="color: white; margin-bottom: 20px; font-size: 1.8rem;">πŸ“„ Content Generator</h2>
<p style="color: white; font-size: 1.1rem; margin-bottom: 20px;">Generate educational content with AI assistance</p>
""")
content_topic = gr.Textbox(label="πŸ“ Topic", placeholder="e.g., Photosynthesis, World War II, Algebra")
content_subject = gr.Dropdown(
choices=["Science", "Mathematics", "History", "English Language Arts", "Geography", "Art"],
label="πŸ“š Subject",
value="Science",
interactive=True
)
content_grade_level = gr.Dropdown(
choices=["K-2", "3-5", "6-8", "9-12"],
label="πŸŽ“ Grade Level",
value="6-8",
interactive=True
)
content_type = gr.Dropdown(
choices=["Study Guide", "Worksheet", "Reading Material", "Summary", "Notes"],
label="πŸ“„ Content Type",
value="Study Guide",
interactive=True
)
content_length = gr.Dropdown(
choices=["Short (1-2 pages)", "Medium (3-5 pages)", "Long (6+ pages)"],
label="πŸ“ Length",
value="Medium (3-5 pages)",
interactive=True
)
content_difficulty = gr.Dropdown(
choices=["Beginner", "Intermediate", "Advanced"],
label="🎯 Difficulty",
value="Intermediate",
interactive=True
)
generate_content_btn = gr.Button("πŸš€ Generate Content", variant="primary")
gr.HTML("</div>")
with gr.Column():
gr.HTML("""
<div class="modern-card slide-in-right">
<h3 style="color: white; margin-bottom: 20px; font-size: 1.4rem;">πŸ“„ Generated Content</h3>
""")
content_progress_display = gr.HTML("", visible=False)
content_output = gr.Markdown(label="")
gr.HTML("</div>")
# Event handler
generate_content_btn.click(
fn=generate_content_with_progress,
inputs=[content_topic, content_subject, content_grade_level, content_difficulty, content_type, content_length],
outputs=[content_progress_display, content_output]
)
def create_feedback_tab():
"""Create the feedback interface"""
with gr.Row():
with gr.Column():
gr.HTML("""
<div class="modern-card slide-in-left">
<h2 style="color: white; margin-bottom: 20px; font-size: 1.8rem;">πŸ’¬ Feedback</h2>
<p style="color: white; font-size: 1.1rem; margin-bottom: 20px;">Help us improve BrightMind AI</p>
""")
feedback_type = gr.CheckboxGroup(
choices=["Lesson Plan Generator", "Quiz Generator", "Content Generator", "Albert Chat", "Overall Experience"],
label="πŸ“‹ What would you like to provide feedback on?",
value=["Overall Experience"]
)
rating = gr.Radio(
choices=[1, 2, 3, 4, 5],
label="⭐ Rating (1-5 stars)",
value=5
)
comments = gr.Textbox(
label="πŸ’­ Comments",
placeholder="Please share your thoughts, suggestions, or any issues you encountered...",
lines=4
)
user_email = gr.Textbox(
label="πŸ“§ Email (optional)",
placeholder="your.email@example.com"
)
submit_feedback_btn = gr.Button("πŸ“€ Submit Feedback", variant="primary")
gr.HTML("</div>")
with gr.Column():
gr.HTML("""
<div class="modern-card slide-in-right">
<h3 style="color: white; margin-bottom: 20px; font-size: 1.4rem;">πŸ“Š Feedback Status</h3>
""")
feedback_status = gr.Markdown("Your feedback helps us improve! Please fill out the form and click submit.")
gr.HTML("</div>")
# Event handler
submit_feedback_btn.click(
fn=submit_feedback,
inputs=[feedback_type, rating, comments, user_email],
outputs=[feedback_status]
)
def create_admin_tab():
"""Create the admin interface"""
with gr.Row():
with gr.Column():
gr.HTML("""
<div class="modern-card slide-in-left">
<h2 style="color: white; margin-bottom: 20px; font-size: 1.8rem;">βš™οΈ Admin Panel</h2>
<p style="color: white; font-size: 1.1rem; margin-bottom: 20px;">View feedback statistics and system information</p>
""")
refresh_stats_btn = gr.Button("πŸ”„ Refresh Statistics", variant="primary")
view_feedback_btn = gr.Button("πŸ“Š View All Feedback", variant="secondary")
gr.HTML("</div>")
with gr.Column():
gr.HTML("""
<div class="modern-card slide-in-right">
<h3 style="color: white; margin-bottom: 20px; font-size: 1.4rem;">πŸ“ˆ Statistics</h3>
""")
stats_display = gr.Markdown("Click 'Refresh Statistics' to view feedback data.")
feedback_display = gr.Markdown("Click 'View All Feedback' to see detailed feedback entries.")
gr.HTML("</div>")
# Event handlers
def refresh_stats():
stats = get_feedback_stats()
return f"""
## πŸ“Š Feedback Statistics
**Total Feedback Entries:** {stats['total_feedback']}
**Average Rating:** {stats['avg_rating']}/5 ⭐
**Recent Feedback:**
{format_recent_feedback(stats['recent_feedback'])}
"""
def view_all_feedback():
return view_feedback_admin()
def format_recent_feedback(recent_feedback):
if not recent_feedback:
return "No recent feedback available."
formatted = ""
for entry in recent_feedback:
timestamp, feedback_type, rating, comments, user_email = entry
formatted += f"- **{timestamp}**: {rating}/5 ⭐ - {comments[:100]}{'...' if len(comments) > 100 else ''}\n"
return formatted
refresh_stats_btn.click(
fn=refresh_stats,
outputs=[stats_display]
)
view_feedback_btn.click(
fn=view_all_feedback,
outputs=[feedback_display]
)