import streamlit as st
import os
from learning_platform import EnhancedCourseBuilder
import asyncio
import nest_asyncio
from datetime import datetime
from sqlalchemy.orm import sessionmaker
from models import create_engine
nest_asyncio.apply()
# Database setup
db_url = os.getenv('DATABASE_URL', 'sqlite:///learning_platform.db')
engine = create_engine(db_url)
Session = sessionmaker(bind=engine)
db_session = Session()
# Page config
st.set_page_config(page_title="MicroGuru", page_icon="🎓", layout="wide")
# Custom CSS
st.markdown("""
""", unsafe_allow_html=True)
# Initialize session state
if 'learning_path' not in st.session_state:
st.session_state.learning_path = None
if 'current_module' not in st.session_state:
st.session_state.current_module = 0
if 'agent_logs' not in st.session_state:
st.session_state.agent_logs = []
if 'completed_courses' not in st.session_state:
st.session_state.completed_courses = []
# Initialize platform
api_key = os.environ.get('OPENAI_API_KEY')
if not api_key:
st.error("⚠️ OpenAI API key not found.")
st.stop()
platform = EnhancedCourseBuilder(api_key, db_session)
def display_agent_logs():
"""Display agent activity logs in sidebar"""
with st.sidebar:
st.markdown("### 🤖 Agent Activity")
for log in st.session_state.agent_logs[-5:]: # Show last 5 logs
st.markdown(f'
{module.title}
""", unsafe_allow_html=True)
# Display objectives
st.markdown("#### 🎯 Learning Objectives")
for obj in module.objectives:
st.markdown(f"- {obj}")
# Display prerequisites if any
if module.prerequisites:
st.markdown("#### 📚 Prerequisites")
for prereq in module.prerequisites:
st.markdown(f"- {prereq}")
if not module.is_complete:
st.info("🔄 Content is being generated... Please wait.")
return
# Display sections
for section in module.sections:
with st.expander(f"📖 {section.title}", expanded=True):
st.markdown(section.content)
st.markdown("#### Key Points")
for point in section.key_points:
st.markdown(f"- {point}")
if section.examples:
st.markdown("#### Examples")
for example in section.examples:
st.code(example)
# Quiz section
st.markdown("""
📝 Knowledge Check
""", unsafe_allow_html=True)
for i, question in enumerate(section.quiz_questions):
st.markdown(f"**Q{i+1}: {question['question']}**")
answer = st.radio(
"Choose your answer:",
question['options'],
key=f"quiz_{section.title}_{i}"
)
if st.button("Check Answer", key=f"check_{section.title}_{i}"):
if answer == question['correct_answer']:
st.success(f"✅ Correct! {question['explanation']}")
else:
st.error(f"❌ Incorrect. {question['explanation']}")
def create_new_course():
"""Handle new course creation"""
st.markdown("### 🚀 Start Your Learning Journey")
with st.form("course_generator"):
topic = st.text_input("What would you like to learn?")
difficulty = st.select_slider(
"Choose difficulty level:",
options=["beginner", "intermediate", "advanced"],
value="intermediate"
)
if st.form_submit_button("Create Course 🎯"):
with st.spinner('Our AI agents are crafting your personalized course...'):
try:
async def create_course():
return await platform.create_course(topic, difficulty, user_id=1)
path = asyncio.run(create_course())
st.session_state.learning_path = path
st.markdown("""
🎉 Your course is ready! Modules are being generated.
×
""", unsafe_allow_html=True)
except Exception as e:
st.error(f"Error: {str(e)}")
def main():
st.title("🎓 MicroGuru")
display_agent_logs()
# Navigation
pages = {
"🏠 Home": create_new_course,
"📚 Current Course": lambda: display_current_course(),
"🏆 Completed Courses": lambda: display_completed_courses()
}
page = st.sidebar.radio("Navigation", list(pages.keys()))
if page == "📚 Current Course" and not st.session_state.learning_path:
st.info("👋 Welcome! Start by creating a new course from the Home page.")
page = "🏠 Home"
pages[page]()
def display_current_course():
"""Display current course content"""
path = st.session_state.learning_path
if not path or len(path.modules) == 0:
st.warning("No modules are available yet. Please wait for the course generation to complete.")
return
display_learning_roadmap()
display_progress_bar()
col1, col2 = st.columns([7, 3])
with col1:
current_module = path.modules[st.session_state.current_module]
display_module_content(current_module)
with col2:
st.markdown("### 📍 Navigation")
# Previous module button
if st.session_state.current_module > 0:
if st.button("⬅️ Previous Module"):
st.session_state.current_module -= 1
st.rerun()
# Next module button
next_idx = st.session_state.current_module + 1
if next_idx < len(path.modules):
if path.modules[next_idx].is_complete:
if st.button("Next Module ➡️"):
st.session_state.current_module = next_idx
st.rerun()
else:
with st.spinner("Generating next module..."):
asyncio.run(
platform.generate_module_content(module_id=path.modules[next_idx].id)
)
st.rerun()
def display_completed_courses():
"""Display completed courses"""
st.markdown("### 🏆 Completed Courses")
if not st.session_state.completed_courses:
st.info("Complete your first course to see it here!")
return
for course in st.session_state.completed_courses:
st.markdown(f"""
{course.topic}
{course.description}
Completed on: {course.completion_date}
""", unsafe_allow_html=True)
if __name__ == "__main__":
main()