-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1930 lines (1657 loc) Β· 89 KB
/
app.py
File metadata and controls
1930 lines (1657 loc) Β· 89 KB
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import time
from datetime import datetime, timedelta, timezone
from typing import Dict, Any, List
from dotenv import load_dotenv
import streamlit as st
from streamlit_ace import st_ace
from streamlit_autorefresh import st_autorefresh
# Load environment variables BEFORE importing services that read env
load_dotenv(override=False)
from src.utils.ui import render_header, render_subheader, animate_lesson_loading
from src.utils.file_ingest import ingest_uploaded_files
from src.services.lesson_planner import generate_lesson_plan
from src.services.code_evaluator import evaluate_code_guidance
from src.services.chroma_store import get_knowledge_store, upsert_learned_concept
from src.services.ollama_client import quick_answer
from src.services.course_service import (
generate_course_structure,
save_course_to_storage,
expand_lesson_plan,
evaluate_summary
)
from src.services.voice_service import speech_to_text, text_to_speech
from src.utils.reporting import save_concept_report
def init_session_state() -> None:
defaults = {
"page": "home",
"cs_view": "root",
"language_view": "root",
"lesson_plan": None,
"learning_objective": None,
"concept_map": None,
"code_language": "Python",
"code_content": "",
"last_guidance": None,
"last_evaluated_at": None,
"chat_history": [],
"uploaded_context": "",
"selected_language": None,
"language_curriculum": None,
"current_language_lesson": None,
"language_chat_history": [],
}
for key, value in defaults.items():
if key not in st.session_state:
st.session_state[key] = value
def set_page(page_name: str) -> None:
st.session_state["page"] = page_name
def set_cs_view(view_name: str) -> None:
st.session_state["cs_view"] = view_name
def set_language_view(view_name: str) -> None:
st.session_state["language_view"] = view_name
def navigate_home() -> None:
set_page("home")
set_cs_view("root")
set_language_view("root")
def render_home() -> None:
render_header("ProfAI")
st.write("Choose a domain to get started. Only Computer Science is functional right now.")
# Add custom CSS for better button styling
st.markdown("""
<style>
.main-menu-button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
border-radius: 15px;
padding: 20px;
margin: 10px 0;
color: white;
font-weight: bold;
font-size: 18px;
box-shadow: 0 8px 25px rgba(0,0,0,0.15);
transition: all 0.3s ease;
cursor: pointer;
text-align: center;
min-height: 120px;
display: flex;
align-items: center;
justify-content: center;
}
.main-menu-button:hover {
transform: translateY(-5px);
box-shadow: 0 12px 35px rgba(0,0,0,0.2);
}
.language-button {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}
.physics-button {
background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
opacity: 0.6;
}
.button-container {
padding: 10px;
}
</style>
""", unsafe_allow_html=True)
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
<div class="button-container">
<div class="main-menu-button" onclick="document.querySelector('#cs-button').click()">
π» Learn Computer Science
</div>
</div>
""", unsafe_allow_html=True)
if st.button("Learn Computer Science", key="cs-button", use_container_width=True, type="primary"):
set_page("cs")
with col2:
st.markdown("""
<div class="button-container">
<div class="main-menu-button language-button" onclick="document.querySelector('#lang-button').click()">
π Learn Languages
</div>
</div>
""", unsafe_allow_html=True)
if st.button("Learn Languages", key="lang-button", use_container_width=True, type="primary"):
set_page("language")
with col3:
st.markdown("""
<div class="button-container">
<div class="main-menu-button physics-button">
β‘ Learn Physics (coming soon)
</div>
</div>
""", unsafe_allow_html=True)
st.button("Learn Physics (coming soon)", use_container_width=True, disabled=True)
def render_cs_root() -> None:
render_header("Computer Science")
render_subheader("How would you like to learn?")
# Add custom CSS for CS submenu buttons
st.markdown("""
<style>
.cs-submenu-button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
border-radius: 12px;
padding: 25px 20px;
margin: 15px 0;
color: white;
font-weight: bold;
font-size: 16px;
box-shadow: 0 6px 20px rgba(0,0,0,0.12);
transition: all 0.3s ease;
cursor: pointer;
text-align: center;
min-height: 100px;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.cs-submenu-button:hover {
transform: translateY(-3px);
box-shadow: 0 10px 30px rgba(0,0,0,0.18);
}
.concept-button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.course-button {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}
.cs-button-container {
padding: 8px;
}
</style>
""", unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
st.markdown("""
<div class="cs-button-container">
<div class="cs-submenu-button concept-button" onclick="document.querySelector('#concept-button').click()">
π§ Learn a New Concept<br>
<small>Master individual topics</small>
</div>
</div>
""", unsafe_allow_html=True)
if st.button("Learn a New Concept", key="concept-button", use_container_width=True, type="primary"):
set_cs_view("new_concept")
with col2:
st.markdown("""
<div class="cs-button-container">
<div class="cs-submenu-button course-button" onclick="document.querySelector('#course-button').click()">
π Take a Course<br>
<small>Structured learning path</small>
</div>
</div>
""", unsafe_allow_html=True)
if st.button("Take a Course", key="course-button", use_container_width=True, type="primary"):
set_cs_view("course_prompt")
if st.button("Back to Home", type="secondary"):
navigate_home()
def render_new_concept_prompt() -> None:
render_header("Learn a New Concept")
prompt = st.text_area("What do you want to learn?", placeholder="e.g., Understand pointers in C and how they relate to linked lists")
uploaded_files = st.file_uploader(
"Optional: Upload supporting files (PDF, TXT, MD)", type=["pdf", "txt", "md"], accept_multiple_files=True
)
if st.button("Generate Lesson Plan", type="primary", use_container_width=True):
if not prompt.strip():
st.warning("Please enter what you want to learn.")
return
# Ingest files
with st.spinner("Ingesting uploaded files..."):
uploaded_context = ingest_uploaded_files(uploaded_files)
st.session_state["uploaded_context"] = uploaded_context
# Generate lesson plan with animation of JSON "thinking"
placeholder = st.empty()
with placeholder.container():
animate_lesson_loading("Loading Code Editor and Lesson Plan")
store = get_knowledge_store()
lesson_plan = generate_lesson_plan(
user_request=prompt,
uploaded_context=st.session_state["uploaded_context"],
knowledge_store=store,
)
# Replace animation with the streamed JSON reveal
placeholder.empty()
animate_lesson_loading(
title="Loading Code Editor and Lesson Plan",
final_content=json.dumps(lesson_plan, indent=2)[:4000],
min_cycles=10,
)
st.session_state["lesson_plan"] = lesson_plan
st.session_state["learning_objective"] = lesson_plan.get("objective")
st.session_state["concept_map"] = lesson_plan.get("concept_map") or lesson_plan.get("milestones")
set_cs_view("editor")
if st.button("Back", type="secondary"):
set_cs_view("root")
def ace_language_from_choice(choice: str) -> str:
mapping = {
"Python": "python",
"C": "c_cpp",
"C++": "c_cpp",
}
return mapping.get(choice, "python")
def render_course_prompt():
"""Render the course generation prompt with course selection"""
st.title("π Take a Course")
# Check for existing courses
from src.services.course_storage import CourseStorage
course_storage = CourseStorage()
existing_courses = course_storage.list_courses()
if existing_courses:
st.subheader("π Existing Courses")
selected_course = st.selectbox(
"Choose an existing course to continue:",
options=existing_courses,
index=0,
format_func=lambda x: x.replace("_", " ").title()
)
if st.button("π Load Course", type="primary"):
course_data = course_storage.get_course_structure(selected_course)
if course_data:
st.session_state["course_structure"] = course_data
st.session_state["course_user_id"] = "default"
set_cs_view("course_map")
st.rerun()
else:
st.error("Failed to load course data")
st.divider()
st.subheader("π Generate New Course")
user_id = st.text_input("User ID (optional):", value="default")
topic = st.text_input("Enter a topic for your course:", placeholder="e.g., Python Programming, Machine Learning, Web Development")
# Add test connection button
if st.button("π Test AI Connection", type="secondary"):
with st.spinner("Testing connection to AI model..."):
from src.services.course_service import _test_ai_connection
if _test_ai_connection():
st.success("β
AI connection successful! Your ngrok server is working.")
else:
st.error("β AI connection failed. Check your ngrok server and model.")
# Add debug button to see raw AI response
if st.button("π Debug AI Response", type="secondary"):
with st.spinner("Testing AI response generation..."):
from src.services.ollama_client import call_model
test_prompt = "Create a simple course structure for 'Python Basics' with 2 sections, each with 2 subsections, each with 2 concepts. Return ONLY valid JSON."
try:
response = call_model([
{"role": "system", "content": "Return ONLY valid JSON."},
{"role": "user", "content": test_prompt}
])
st.text_area("Raw AI Response:", response, height=200)
st.json({"response_length": len(response), "preview": response[:500]})
except Exception as e:
st.error(f"Debug failed: {str(e)}")
# Add debug button to show session state
if st.button("π Show Session State", type="secondary"):
st.json({
"course_structure_exists": "course_structure" in st.session_state,
"course_user_id": st.session_state.get("course_user_id", "Not set"),
"current_page": st.session_state.get("page", "Not set"),
"current_cs_view": st.session_state.get("cs_view", "Not set")
})
if st.button("Generate Course", type="primary"):
if not topic.strip():
st.warning("Please enter a topic.")
return
# Clear old course data
if "course_structure" in st.session_state:
del st.session_state["course_structure"]
if "course_user_id" in st.session_state:
del st.session_state["course_user_id"]
with st.spinner("Generating course structure (7x10x10)..."):
course = generate_course_structure(user_id=user_id, topic=topic)
# Debug output
st.info(f"π Generated course structure:")
st.json({
"course_name": course.get("course", "Unknown"),
"sections_count": len(course.get("sections", [])),
"first_section": course.get("sections", [{}])[0].get("name", "None") if course.get("sections") else "None",
"structure_type": "AI Generated" if "sections" in course and len(course["sections"]) > 0 else "Mock Data"
})
st.session_state["course_structure"] = course
st.session_state["course_user_id"] = user_id
set_cs_view("course_map")
if st.button("Back", type="secondary"):
set_cs_view("root")
def render_course_map():
"""Render the interactive course map with detailed lesson plans"""
if "course_structure" not in st.session_state:
st.error("No course structure found. Please generate a course first.")
return
course = st.session_state["course_structure"]
course_name = course.get("course", "Unknown Course")
# Get course progress from storage
from src.services.course_storage import CourseStorage
course_storage = CourseStorage()
progress = course_storage.get_course_progress(course_name)
st.title(f"π {course_name} - Course Map")
# Show course metadata
try:
course_dir = course_storage.base_dir / course_storage._safe_name(course_name)
if course_dir.exists():
course_structure_file = course_dir / "course_structure.json"
if course_structure_file.exists():
with open(course_structure_file, "r") as f:
course_data = json.load(f)
created_at = course_data.get("created_at", "Unknown")
if created_at != "Unknown":
try:
from datetime import datetime
created_dt = datetime.fromisoformat(created_at.replace('Z', '+00:00'))
st.caption(f"π
Course created: {created_dt.strftime('%Y-%m-%d %H:%M')}")
except:
st.caption(f"π
Course created: {created_at}")
except Exception as e:
pass # Ignore errors in metadata display
# Show progress summary
if "error" not in progress:
col1, col2, col3, col4, col5 = st.columns(5)
with col1:
st.metric("Total Lessons", progress["total_lessons"])
with col2:
st.metric("Completed", progress["completed_lessons"])
with col3:
st.metric("Progress", f"{progress['completion_percentage']:.1f}%")
with col4:
total_hours = progress.get("total_time_minutes", 0) / 60
st.metric("Total Time", f"{total_hours:.1f} hours")
with col5:
if progress["completed_lessons"] > 0:
avg_time = progress.get("total_time_minutes", 0) / progress["completed_lessons"]
st.metric("Avg/Lesson", f"{avg_time:.1f} min")
else:
st.metric("Avg/Lesson", "N/A")
# Add estimated time remaining
if progress["completed_lessons"] > 0 and progress["total_lessons"] > progress["completed_lessons"]:
avg_time = progress.get("total_time_minutes", 0) / progress["completed_lessons"]
remaining_lessons = progress["total_lessons"] - progress["completed_lessons"]
estimated_remaining = avg_time * remaining_lessons
st.info(f"β±οΈ Estimated time remaining: {estimated_remaining:.1f} minutes ({estimated_remaining/60:.1f} hours)")
# Course structure using tabs for modules
sections = course.get("sections", [])
if sections:
# Create tabs for each module
module_tabs = st.tabs([f"π Module {i+1}: {s['name']}" for i, s in enumerate(sections)])
for section_idx, (section, tab) in enumerate(zip(sections, module_tabs)):
with tab:
subsections = section.get("subsections", [])
# Use columns to show subsections
for sub_idx, subsection in enumerate(subsections):
st.subheader(f"π Submodule {sub_idx + 1}: {subsection['name']}")
concepts = subsection.get("concepts", [])
# Display concepts in a grid
for concept_idx, concept in enumerate(concepts):
# Check if detailed plan exists
detailed_plan = course_storage.get_detailed_lesson_plan(
course_name, section_idx + 1, sub_idx + 1, concept_idx + 1
)
# Create a unique key for this lesson
lesson_key = f"lesson_{section_idx}_{sub_idx}_{concept_idx}"
# Check lesson status
from src.services.course_storage import CourseStorage
course_storage = CourseStorage()
is_completed = course_storage.is_lesson_completed(
course_name, section_idx + 1, sub_idx + 1, concept_idx + 1
)
has_saved_code = course_storage.get_lesson_code(
course_name, section_idx + 1, sub_idx + 1, concept_idx + 1
) is not None
# Get completion time if completed
completion_time = None
last_code_update = None
time_spent = None
if is_completed:
lesson_dir = course_storage._get_lesson_directory(
course_name, section_idx + 1, sub_idx + 1, concept_idx + 1
)
if lesson_dir:
concept_info_file = lesson_dir / "concept_info.json"
if concept_info_file.exists():
with open(concept_info_file, "r") as f:
concept_info = json.load(f)
completion_time = concept_info.get("completed_at")
last_code_update = concept_info.get("last_code_update")
time_spent = concept_info.get("total_time_minutes")
elif has_saved_code:
lesson_dir = course_storage._get_lesson_directory(
course_name, section_idx + 1, sub_idx + 1, concept_idx + 1
)
if lesson_dir:
concept_info_file = lesson_dir / "concept_info.json"
if concept_info_file.exists():
with open(concept_info_file, "r") as f:
concept_info = json.load(f)
last_code_update = concept_info.get("last_code_update")
time_spent = concept_info.get("total_time_minutes")
# Determine status icon and color
if is_completed:
status_icon = "β
"
status_color = "success"
elif has_saved_code:
status_icon = "π"
status_color = "warning"
else:
status_icon = "β³"
status_color = "info"
# Create an expander for each concept
with st.expander(f"{status_icon} **{concept_idx + 1}. {concept['name']}** - {concept['agenda']}", expanded=False):
col1, col2 = st.columns([4, 1])
with col1:
st.write(f"**Agenda:** {concept['agenda']}")
# Show completion time if completed
if completion_time:
try:
from datetime import datetime
completion_dt = datetime.fromisoformat(completion_time.replace('Z', '+00:00'))
st.success(f"β
Completed on {completion_dt.strftime('%Y-%m-%d %H:%M')}")
except:
st.success(f"β
Completed")
# Show last code update time if available
if last_code_update:
try:
from datetime import datetime
update_dt = datetime.fromisoformat(last_code_update.replace('Z', '+00:00'))
st.info(f"π» Last updated: {update_dt.strftime('%Y-%m-%d %H:%M')}")
except:
st.info(f"π» Has saved code")
# Show time spent if available
if time_spent:
st.info(f"β±οΈ Time spent: {time_spent} minutes")
# Show detailed plan if it exists
if detailed_plan:
st.markdown("---")
st.markdown("**π Detailed Lesson Plan:**")
st.markdown(detailed_plan)
# Show YouTube videos if they exist
youtube_videos = course_storage.get_youtube_videos(
course_name, section_idx + 1, sub_idx + 1, concept_idx + 1
)
if youtube_videos:
st.markdown("---")
st.markdown("**π¬ Related YouTube Videos:**")
for i, video in enumerate(youtube_videos, 1):
st.markdown(f"**πΊ Video {i}: {video.get('title', 'Unknown Title')}**")
st.markdown(f"**Channel:** {video.get('channel', 'Unknown')}")
st.markdown(f"**URL:** [{video.get('url', '#')}]({video.get('url', '#')})")
# Show AI explanation if available
if video.get('explanation'):
st.markdown("**π€ Why This Video is Relevant:**")
st.markdown(video.get('explanation'))
st.markdown("**π Summary:**")
st.markdown(video.get('summary', 'No summary available'))
if i < len(youtube_videos):
st.divider()
else:
st.info("No detailed lesson plan yet. Click 'Expand Lesson' to generate one.")
# Check if lesson has saved code (in progress)
from src.services.course_storage import CourseStorage
course_storage = CourseStorage()
has_saved_code = course_storage.get_lesson_code(
course_name, section_idx + 1, sub_idx + 1, concept_idx + 1
) is not None
# Add Start/Continue Lesson button
button_text = "π Continue Lesson" if has_saved_code else "π― Start Lesson"
button_type = "secondary" if has_saved_code else "primary"
if st.button(button_text, key=f"start_lesson_{lesson_key}", type=button_type):
# Set the current lesson context
st.session_state["current_lesson"] = {
"course_name": course_name,
"module_idx": section_idx + 1,
"submodule_idx": sub_idx + 1,
"lesson_idx": concept_idx + 1,
"module_name": section["name"],
"submodule_name": subsection["name"],
"lesson_name": concept["name"],
"agenda": concept["agenda"],
"detailed_plan": detailed_plan
}
set_cs_view("lesson_workspace")
st.rerun()
with col2:
if not detailed_plan:
if st.button(f"π Expand", key=f"expand_{lesson_key}"):
with st.spinner("Generating detailed lesson plan..."):
try:
detailed_plan = expand_lesson_plan(
course_name, section_idx + 1, sub_idx + 1, concept_idx + 1
)
if detailed_plan and not detailed_plan.startswith("Error"):
st.success("β
Lesson plan expanded!")
st.rerun()
else:
st.error(f"Failed to expand: {detailed_plan}")
except Exception as e:
st.error(f"Error during expansion: {str(e)}")
else:
st.success("β
Completed")
# Add View Code button for completed lessons
if st.button(f"π» View Code", key=f"view_code_{lesson_key}"):
from src.services.course_storage import CourseStorage
course_storage = CourseStorage()
saved_code = course_storage.get_lesson_code(
course_name, section_idx + 1, sub_idx + 1, concept_idx + 1
)
if saved_code:
st.code(saved_code, language="python")
else:
st.info("No code saved for this lesson yet.")
if st.button(f"π Regenerate", key=f"regenerate_{lesson_key}"):
with st.spinner("Regenerating detailed lesson plan..."):
try:
detailed_plan = expand_lesson_plan(
course_name, section_idx + 1, sub_idx + 1, concept_idx + 1
)
if detailed_plan and not detailed_plan.startswith("Error"):
st.success("β
Lesson plan regenerated!")
st.rerun()
else:
st.error(f"Failed to regenerate: {detailed_plan}")
except Exception as e:
st.error(f"Error during regeneration: {str(e)}")
# Add some spacing between concepts
if concept_idx < len(concepts) - 1:
st.divider()
# Add spacing between subsections
if sub_idx < len(subsections) - 1:
st.markdown("---")
# Add course management options
st.divider()
col1, col2, col3, col4 = st.columns(4)
with col1:
if st.button("π Refresh Progress"):
st.rerun()
with col2:
if st.button("π Export Progress"):
st.json(progress)
with col3:
if st.button("π Back to Course Selection"):
set_cs_view("course_prompt")
with col4:
if st.button("π Debug Course"):
st.subheader("π Course Debug Information")
# Show course structure info
st.write("**Course Structure:**")
st.json({
"course_name": course_name,
"total_sections": len(sections),
"first_section_name": sections[0]["name"] if sections else "None",
"first_subsection_name": sections[0]["subsections"][0]["name"] if sections and sections[0]["subsections"] else "None",
"first_concept_name": sections[0]["subsections"][0]["concepts"][0]["name"] if sections and sections[0]["subsections"] and sections[0]["subsections"][0]["concepts"] else "None"
})
# Show storage info
st.write("**Storage Information:**")
try:
# Test getting a lesson agenda
test_agenda = course_storage.get_lesson_agenda(course_name, 1, 1, 1)
st.write(f"Test Lesson Agenda (1,1,1): {test_agenda[:100] if test_agenda else 'None'}...")
# Test getting detailed plan
test_plan = course_storage.get_detailed_lesson_plan(course_name, 1, 1, 1)
st.write(f"Test Detailed Plan (1,1,1): {test_plan[:100] if test_plan else 'None'}...")
# Show course directory structure
course_dir = course_storage.base_dir / course_storage._safe_name(course_name)
if course_dir.exists():
st.write(f"**Course Directory:** {course_dir}")
st.write("**Directory Contents:**")
for item in list(course_dir.iterdir())[:5]: # Show first 5 items
st.write(f" - {item.name}")
else:
st.write("**Course Directory:** Does not exist")
except Exception as e:
st.error(f"Debug error: {str(e)}")
def render_lesson_workspace() -> None:
"""Render the interactive lesson workspace with code editor for course lessons"""
if "current_lesson" not in st.session_state:
st.error("No lesson selected. Please go back to the course map.")
if st.button("Back to Course Map"):
set_cs_view("course_map")
return
lesson = st.session_state["current_lesson"]
course_name = lesson["course_name"]
module_name = lesson["module_name"]
submodule_name = lesson["submodule_name"]
lesson_name = lesson["lesson_name"]
agenda = lesson["agenda"]
detailed_plan = lesson.get("detailed_plan")
# Auto refresh every 20 seconds to trigger re-evaluation
_ = st_autorefresh(interval=20000, key="auto_refresh_lesson_workspace")
# Header with breadcrumb navigation
st.title(f"π― {lesson_name}")
st.caption(f"π {course_name} β π {module_name} β π {submodule_name}")
# Three-column layout as specified: left (1/3), center (2/3), right (guidance)
left_col, center_col, right_col = st.columns([1, 2, 1])
with left_col:
# Top half: Concept map/problem statement with learning objective
st.markdown("### π― Learning Objective")
st.write(agenda)
if detailed_plan:
with st.expander("π Detailed Lesson Plan", expanded=True):
st.markdown(detailed_plan)
# Show YouTube videos if they exist
from src.services.course_storage import CourseStorage
course_storage = CourseStorage()
youtube_videos = course_storage.get_youtube_videos(
course_name,
lesson["module_idx"],
lesson["submodule_idx"],
lesson["lesson_idx"]
)
if youtube_videos:
st.markdown("---")
st.markdown("**π¬ Related YouTube Videos:**")
for i, video in enumerate(youtube_videos, 1):
st.markdown(f"**πΊ Video {i}: {video.get('title', 'Unknown Title')}**")
st.markdown(f"**Channel:** {video.get('channel', 'Unknown')}")
st.markdown(f"**URL:** [{video.get('url', '#')}]({video.get('url', '#')})")
# Show AI explanation if available
if video.get('explanation'):
st.markdown("**π€ Why This Video is Relevant:**")
st.markdown(video.get('explanation'))
st.markdown("**π Summary:**")
st.markdown(video.get('summary', 'No summary available'))
if i < len(youtube_videos):
st.divider()
else:
st.info("No detailed lesson plan available yet.")
# Bottom half: Chatbox for quick clarifications
st.markdown("### π¬ Quick Help Chat")
with st.form("lesson_quick_help"):
quick_q = st.text_input("Ask a question about this lesson")
submitted = st.form_submit_button("Ask")
if submitted and quick_q.strip():
with st.spinner("Thinking..."):
# Use the lesson context for better answers
context = f"Course: {course_name}, Module: {module_name}, Submodule: {submodule_name}, Lesson: {lesson_name}, Agenda: {agenda}"
if detailed_plan:
context += f"\n\nDetailed Plan: {detailed_plan}"
answer = quick_answer(quick_q, context=context)
st.session_state.setdefault("lesson_chat_history", []).append({"q": quick_q, "a": answer})
# Show chat history
if st.session_state.get("lesson_chat_history"):
st.markdown("**Recent Questions:**")
for idx, turn in enumerate(reversed(st.session_state["lesson_chat_history"][-5:])): # Show last 5
st.markdown(f"**Q:** {turn['q']}")
st.markdown(f"**A:** {turn['a'][:100]}...")
if idx > 2: # Limit display
break
with center_col:
st.markdown("### π» Code Editor")
# Language selector (C, C++, or Python)
lang = st.selectbox("Programming Language", ["Python", "C", "C++"],
index=0, # Default to Python
key="lesson_editor_lang")
# Load previously saved code if it exists
if "lesson_code_content" not in st.session_state:
from src.services.course_storage import CourseStorage
course_storage = CourseStorage()
saved_code = course_storage.get_lesson_code(
course_name,
lesson["module_idx"],
lesson["submodule_idx"],
lesson["lesson_idx"]
)
if saved_code:
st.session_state["lesson_code_content"] = saved_code
# ST_ACE code editor
code = st_ace(
value=st.session_state.get("lesson_code_content", ""),
language=ace_language_from_choice(lang),
theme="tomorrow_night",
height=550,
show_gutter=True,
show_print_margin=False,
wrap=True,
auto_update=True,
key="lesson_ace_editor",
)
if code is not None:
st.session_state["lesson_code_content"] = code
# Action buttons
col1, col2, col3 = st.columns(3)
with col1:
if st.button("πΎ Save Progress"):
# Save the current lesson progress
from src.services.course_storage import CourseStorage
course_storage = CourseStorage()
# Mark lesson as completed
course_storage.mark_lesson_completed(
course_name,
lesson["module_idx"],
lesson["submodule_idx"],
lesson["lesson_idx"]
)
# Save code content
course_storage.save_lesson_code(
course_name,
lesson["module_idx"],
lesson["submodule_idx"],
lesson["lesson_idx"],
st.session_state.get("lesson_code_content", "")
)
st.success("Progress saved!")
with col2:
if st.button("π Show Progress"):
from src.services.course_storage import CourseStorage
course_storage = CourseStorage()
progress = course_storage.get_course_progress(course_name)
st.json(progress)
with col3:
if st.button("π Back to Map", type="secondary"):
set_cs_view("course_map")
st.rerun()
with right_col:
st.markdown("### π― Guidance Panel")
# Auto-evaluate every 20 seconds
now = datetime.now(timezone.utc)
last_eval_iso = st.session_state.get("lesson_last_evaluated_at")
should_eval = False
if last_eval_iso is None:
should_eval = True if st.session_state.get("lesson_code_content") else False
else:
try:
last_eval = datetime.fromisoformat(last_eval_iso)
should_eval = (now - last_eval) >= timedelta(seconds=20)
except Exception:
should_eval = True
if should_eval and st.session_state.get("lesson_code_content"):
with st.spinner("Auto-evaluating your code..."):
guidance = evaluate_code_guidance(
objective=agenda,
code=st.session_state.get("lesson_code_content", ""),
language=lang,
)
st.session_state["lesson_last_guidance"] = guidance
st.session_state["lesson_last_evaluated_at"] = now.isoformat()
if st.session_state.get("lesson_last_guidance"):
st.markdown("**π‘ Directional Hints (No Solutions):**")
st.write(st.session_state["lesson_last_guidance"])
# Lesson completion status
st.markdown("### β
Lesson Status")
from src.services.course_storage import CourseStorage
course_storage = CourseStorage()
is_completed = course_storage.is_lesson_completed(
course_name,
lesson["module_idx"],
lesson["submodule_idx"],
lesson["lesson_idx"]
)
if is_completed:
st.success("π Lesson Completed!")
else:
st.info("π Lesson in Progress")
# Voice-based learning evaluation - Always available
st.divider()
st.markdown("### π€ Voice-Based Learning Check")
st.caption("Record a verbal summary of what you learned. We'll evaluate your understanding and create a learning pattern.")
# Initialize voice evaluation state
if "lesson_voice_attempt" not in st.session_state:
st.session_state["lesson_voice_attempt"] = 1
if "lesson_voice_transcript" not in st.session_state:
st.session_state["lesson_voice_transcript"] = ""
if "lesson_voice_gap_report" not in st.session_state:
st.session_state["lesson_voice_gap_report"] = None
if "lesson_voice_final_report" not in st.session_state:
st.session_state["lesson_voice_final_report"] = None
col1, col2, col3 = st.columns([1, 1, 1])
with col1:
# Always show the recording interface
st.markdown("**π€ Live Voice Recording:**")
# Live recording interface using HTML/JavaScript
recording_html = """
<div style="text-align: center; padding: 20px; border: 2px solid #e74c3c; border-radius: 10px; background-color: #f8f9fa;">
<h4>π€ Live Voice Recording</h4>
<div id="recording-status" style="margin: 10px 0; font-weight: bold; color: #6c757d;">Ready to record</div>
<div style="margin: 15px 0;">
<button id="testMic" onclick="testMicrophone()" style="background-color: #17a2b8; color: white; border: none; padding: 8px 16px; border-radius: 5px; margin: 5px; cursor: pointer; font-size: 12px;">π Test Microphone</button>
<button id="startRecord" onclick="startRecording()" style="background-color: #e74c3c; color: white; border: none; padding: 10px 20px; border-radius: 5px; margin: 5px; cursor: pointer;">π€ Start Recording</button>
<button id="stopRecord" onclick="stopRecording()" style="background-color: #6c757d; color: white; border: none; padding: 10px 20px; border-radius: 5px; margin: 5px; cursor: pointer; display: none;">βΉοΈ Stop Recording</button>
</div>
<div id="audioPlayer" style="margin: 10px 0; display: none;">
<audio id="recordedAudio" controls style="width: 100%;"></audio>
</div>
<div id="downloadSection" style="margin: 10px 0; display: none;">
<button onclick="downloadAudio()" style="background-color: #28a745; color: white; border: none; padding: 8px 16px; border-radius: 5px; cursor: pointer;">πΎ Download Audio</button>
</div>
</div>
<script>
let mediaRecorder;
let audioChunks = [];
let audioBlob;
let testStream;
async function startRecording() {
try {
// Check if microphone is available
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
throw new Error('Microphone not supported in this browser');
}
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
sampleRate: 44100
}
});
mediaRecorder = new MediaRecorder(stream, {
mimeType: 'audio/webm;codecs=opus'
});
audioChunks = [];
mediaRecorder.ondataavailable = (event) => {
audioChunks.push(event.data);
};
mediaRecorder.onstop = () => {
audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
const audioUrl = URL.createObjectURL(audioBlob);
document.getElementById('recordedAudio').src = audioUrl;
document.getElementById('audioPlayer').style.display = 'block';
document.getElementById('downloadSection').style.display = 'block';
document.getElementById('recording-status').textContent = 'β
Recording completed!';
document.getElementById('recording-status').style.color = '#28a745';
// Store the audio blob in session storage for Streamlit
const reader = new FileReader();
reader.onload = function() {
const base64Audio = reader.result.split(',')[1];
sessionStorage.setItem('recordedAudio', base64Audio);
};
reader.readAsDataURL(audioBlob);
};