File size: 9,722 Bytes
e9c994c
 
d7706d6
e9c994c
 
579445a
d7706d6
 
48f28da
e9c994c
 
d7706d6
 
 
 
 
 
e9c994c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66e9fea
 
e9c994c
66e9fea
e9c994c
66e9fea
 
 
 
 
 
 
 
 
 
e9c994c
 
 
 
 
 
 
 
 
 
 
 
bc1abf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9c994c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7706d6
e9c994c
 
 
 
 
 
 
 
 
 
 
 
 
bc1abf3
 
 
e9c994c
 
 
 
 
 
 
 
 
 
66e9fea
 
 
 
 
 
 
 
 
 
 
 
 
 
e9c994c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66e9fea
e9c994c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f28da
e9c994c
 
 
 
 
d7706d6
e9c994c
 
 
bc1abf3
 
 
 
 
 
e9c994c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc1abf3
 
 
66e9fea
e9c994c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7706d6
e9c994c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
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("""
<style>
.agent-log {
    padding: 8px;
    margin: 4px 0;
    border-radius: 4px;
    background: #f0f7ff;
    border-left: 3px solid #1e88e5;
}
.module-card {
    padding: 20px;
    background: white;
    border-radius: 8px;
    border-left: 4px solid #4caf50;
    margin: 10px 0;
    cursor: pointer;
    transition: background 0.3s ease;
}
.module-card:hover {
    background: #f5f5f5;
}
.loading-icon {
    font-size: 1.5em;
    color: #1e88e5;
    margin-right: 10px;
}
.completed-icon {
    font-size: 1.5em;
    color: #4caf50;
    margin-right: 10px;
}
.progress-bar {
    height: 20px;
    background: #e0e0e0;
    border-radius: 10px;
    overflow: hidden;
}
.progress-value {
    height: 100%;
    background: #4caf50;
    transition: width 0.5s ease-in-out;
}
.alert {
    position: relative;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #4caf50;
    background-color: #dff0d8;
}
.alert .close {
    position: absolute;
    top: 10px;
    right: 10px;
    cursor: pointer;
    font-size: 1.5em;
}
</style>
""", 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'<div class="agent-log">{log}</div>', unsafe_allow_html=True)

def display_progress_bar():
    """Display course progress bar"""
    if st.session_state.learning_path:
        path = st.session_state.learning_path
        total_modules = len(path.modules)
        if total_modules == 0:
            st.warning("No modules available in the course.")
            return
        current = st.session_state.current_module + 1
        progress = (current / total_modules) * 100
        
        st.markdown(f"""
        <div class="progress-bar">
            <div class="progress-value" style="width: {progress}%"></div>
        </div>
        <p style="text-align: center">Module {current}/{total_modules}</p>
        """, unsafe_allow_html=True)

def display_learning_roadmap():
    """Display the learning roadmap with module cards"""
    st.markdown("### πŸ›£οΈ Learning Roadmap")
    path = st.session_state.learning_path
    for i, module in enumerate(path.modules):
        status_icon = "" if module.is_complete else "<i class='loading-icon'>&#8987;</i>"
        is_clickable = "true" if module.is_complete else "false"
        st.markdown(f"""
        <div class="module-card" onclick="if({is_clickable}) {{ location.href='#module-{i}'; }}">
            {status_icon}<h4 id="module-{i}">{module.title}</h4>
            <p>{module.description}</p>
        </div>
        """, unsafe_allow_html=True)

def display_module_content(module):
    """Display module content and quiz"""
    st.markdown(f"""
    <div class="module-card">
        <h3>{module.title}</h3>
    """, 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("""
            <div class="quiz-card">
                <h4>πŸ“ Knowledge Check</h4>
            </div>
            """, 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("""
                    <div class="alert">
                        πŸŽ‰ Your course is ready! Modules are being generated.
                        <span class="close" onclick="this.parentElement.style.display='none';">&times;</span>
                    </div>
                    """, 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"""
        <div class="module-card">
            <h4>{course.topic}</h4>
            <p>{course.description}</p>
            <p><small>Completed on: {course.completion_date}</small></p>
        </div>
        """, unsafe_allow_html=True)

if __name__ == "__main__":
    main()