-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
2058 lines (1879 loc) · 86.6 KB
/
Copy pathstreamlit_app.py
File metadata and controls
2058 lines (1879 loc) · 86.6 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 html
import os
import re
import tempfile
from pathlib import Path
# CRITICAL FIX: Unset CLAUDECODE before any other imports
# This allows the app to use Claude Code even when run from within Claude Code
if "CLAUDECODE" in os.environ:
del os.environ["CLAUDECODE"]
import streamlit as st
from app.ai_generator import (
ABOUT_COURSE_PROMPT_TEMPLATE,
ASSESSMENT_METHOD_PROMPT_TEMPLATE,
ASSESSMENT_METHODS_LIST,
BACKGROUND_PART_A_PROMPT_TEMPLATE,
BACKGROUND_PART_B_PROMPT_TEMPLATE,
COURSE_TITLE_SUGGESTIONS_PROMPT_TEMPLATE,
COURSE_OUTLINE_PROMPT_TEMPLATE,
COURSE_TOPICS_PROMPT_TEMPLATE,
COURSE_VALIDATION_PROMPT_TEMPLATE,
INSTRUCTION_METHOD_PROMPT_TEMPLATE,
LEARNING_OUTCOME_PROMPT_TEMPLATE,
LESSON_PLAN_PROMPT_TEMPLATE,
INSTRUCTION_METHODS_LIST,
LU_SEQUENCING_TYPES,
LU_SEQUENCING_TEMPLATES,
UNIQUE_SKILL_NAMES_LIST,
SKILL_DESCRIPTIONS,
JOB_ROLES_PROMPT_TEMPLATE,
MINIMUM_ENTRY_REQUIREMENT_PROMPT_TEMPLATE,
WHAT_YOULL_LEARN_PROMPT_TEMPLATE,
generate_about_course,
generate_assessment_method,
generate_background_part_a,
generate_background_part_b,
generate_course_title_suggestions,
generate_course_outline,
generate_course_topics,
generate_course_validation,
generate_instruction_method,
generate_learning_outcomes,
generate_lesson_plan_content,
parse_ai_lesson_plan,
generate_lu_sequencing_rationale,
generate_job_roles,
generate_minimum_entry_requirement,
generate_what_youll_learn,
)
from app.extractor import build_course_outline, build_course_topics, extract_data
from app.simple_lesson_plan import DEFAULT_RESOURCES, build_simple_lesson_plan
from app.generator_docx import generate_audit_report
from app.generator_lesson_plan import (
generate_lesson_plan_table,
generate_simple_lesson_plan_docx,
)
from app.generator_lesson_plan_pdf import (
generate_lesson_plan_pdf_table,
generate_simple_lesson_plan_pdf,
)
st.set_page_config(page_title="CASL Course Document Generator", page_icon="📄", layout="wide")
LIGHT_THEME_CSS = """
<style>
:root { color-scheme: light; }
.stApp, [data-testid="stHeader"], [data-testid="stAppViewContainer"] {
background-color: #ffffff;
color: #1a1a1a;
}
[data-testid="stSidebar"] { background-color: #f3f4f6; }
[data-testid="stSidebar"] * { color: #1a1a1a; }
.stApp h1, .stApp h2, .stApp h3, .stApp h4, .stApp h5, .stApp h6,
.stApp p, .stApp li, .stApp label, .stApp span,
[data-testid="stMarkdownContainer"], [data-testid="stWidgetLabel"] {
color: #1a1a1a;
}
/* Inputs, text areas, number inputs, selects */
.stApp input, .stApp textarea,
[data-baseweb="input"], [data-baseweb="textarea"], [data-baseweb="select"] > div {
background-color: #ffffff !important;
color: #1a1a1a !important;
}
/* Dropdown / popover menus (rendered in portals) */
[data-baseweb="popover"], [data-baseweb="menu"], [role="listbox"] {
background-color: #ffffff !important;
color: #1a1a1a !important;
}
[role="option"] { color: #1a1a1a !important; }
/* Multiselect chips */
[data-baseweb="tag"] { color: #ffffff !important; }
/* Code blocks */
.stApp pre, .stApp code { background-color: #f3f4f6 !important; color: #1a1a1a !important; }
/* Dataframes */
[data-testid="stDataFrame"] { background-color: #ffffff; }
/* Secondary (non-primary) buttons */
.stButton button[kind="secondary"] {
background-color: #ffffff !important;
color: #1a1a1a !important;
border: 1px solid #d0d0d0 !important;
}
/* Expander */
[data-testid="stExpander"] details {
background-color: #f8f9fa !important;
border: 1px solid #e0e0e0 !important;
}
</style>
"""
BASE_CSS = """
<style>
/* Trim the large default top padding above the page content */
.block-container, [data-testid="stMainBlockContainer"] {
padding-top: 3rem;
}
/* Hide the unused Deploy button so the theme toggle has room top-right */
[data-testid="stAppDeployButton"] { display: none; }
/* Keep the theme toggle compact and on one line */
[data-testid="stMain"] [data-testid="stToggle"] label p { white-space: nowrap; }
</style>
"""
def apply_theme(light: bool) -> None:
"""Apply the selected theme. Dark is handled by .streamlit/config.toml;
light mode injects CSS overrides at runtime."""
st.markdown(BASE_CSS, unsafe_allow_html=True)
if light:
st.markdown(LIGHT_THEME_CSS, unsafe_allow_html=True)
def _render_lesson_plan_table(rows: list[dict]) -> str:
"""Render a day's lesson plan rows as a theme-friendly HTML table that wraps
long topic text and shows all four columns within the container width."""
cols = [
("Time", "time", "15%"),
("Topics", "topic", "45%"),
("Instructional Methods", "method", "22%"),
("Resources", "resources", "18%"),
]
border = "1px solid rgba(128,128,128,0.4)"
th = (
f"text-align:left;padding:6px 10px;border:{border};"
"font-weight:600;vertical-align:top;"
)
td = f"padding:6px 10px;border:{border};vertical-align:top;"
head = "".join(
f'<th style="{th}width:{w};">{html.escape(label)}</th>' for label, _, w in cols
)
body = ""
for r in rows:
body += "<tr>" + "".join(
f'<td style="{td}">{html.escape(str(r[key]))}</td>' for _, key, _ in cols
) + "</tr>"
return (
'<table style="width:100%;border-collapse:collapse;font-size:0.9rem;'
f'margin-bottom:0.5rem;"><thead><tr>{head}</tr></thead><tbody>{body}</tbody></table>'
)
def populate_session_from_cp(data) -> list[str]:
"""Populate all session state from an extracted CP so every page is pre-filled.
Returns the list of section labels that were populated.
"""
p = data.particulars
populated: list[str] = []
# --- Course Details: title & topics ---
if p.course_title:
st.session_state["saved_course_title"] = p.course_title
st.session_state["cd_course_title"] = p.course_title
populated.append("Course Title")
topics_md = build_course_topics(data)
if topics_md:
st.session_state["saved_course_topics"] = topics_md
st.session_state["cd_course_topics"] = topics_md
st.session_state["saved_num_topics"] = len(data.learning_outcomes)
populated.append("Course Topics")
# --- Course Details: durations (derived from CP durations) ---
instr_min = sum(lo.duration_minutes for lo in data.learning_outcomes)
assess_min = sum(a.duration_minutes for a in data.assessment_modes)
if instr_min:
st.session_state["saved_instructional_duration"] = max(1, round(instr_min / 60))
st.session_state["saved_assessment_duration"] = round(assess_min / 60) if assess_min else 0
total_min = instr_min + assess_min
if total_min:
st.session_state["saved_course_duration"] = max(1, round(total_min / 60))
# --- Course Details: methods (filtered to known options) ---
valid_im = [m for m in data.instruction_method_descriptions if m in INSTRUCTION_METHODS_LIST]
if valid_im:
st.session_state["saved_instr_methods"] = valid_im
st.session_state["saved_num_instr_methods"] = len(valid_im)
valid_am = [m for m in data.assessment_method_descriptions if m in ASSESSMENT_METHODS_LIST]
st.session_state["saved_assess_methods"] = valid_am
st.session_state["saved_num_assess_methods"] = len(valid_am)
# --- Course Details: CASL unique skill name ---
if st.session_state.get("cp_mode") == "CASL" and p.unique_skill_names:
usn = p.unique_skill_names[0]
if usn in UNIQUE_SKILL_NAMES_LIST:
st.session_state["saved_unique_skill_name"] = usn
st.session_state["cd_unique_skill_name"] = usn
# --- Generated text sections ---
if p.about_course:
st.session_state["about_course_text"] = p.about_course
populated.append("About This Course")
if p.what_youll_learn:
st.session_state["wyl_text"] = p.what_youll_learn
populated.append("What You'll Learn")
if data.background.targeted_sectors:
st.session_state["bg_text"] = data.background.targeted_sectors
populated.append("Background Part A")
if data.background.performance_gaps:
st.session_state["bgb_text"] = data.background.performance_gaps
populated.append("Background Part B")
if data.instruction_method_descriptions:
st.session_state["im_results"] = dict(data.instruction_method_descriptions)
populated.append("Instructional Methods")
if data.assessment_method_descriptions:
st.session_state["am_results"] = dict(data.assessment_method_descriptions)
populated.append("Assessment Methods")
# --- Course Outline ---
st.session_state["co_text"] = build_course_outline(data)
populated.append("Course Outline")
return populated
# --- Sidebar Navigation ---
if "active_page" not in st.session_state:
st.session_state["active_page"] = "Course Details"
with st.sidebar:
st.title("WSQ/CASL CP Generator")
cp_mode = st.radio("Mode", ["CASL", "WSQ"], horizontal=True, key="cp_mode", label_visibility="collapsed")
st.markdown("---")
st.caption("PREPARE CP")
if st.button("Course Details", use_container_width=True,
type="primary" if st.session_state["active_page"] == "Course Details" else "secondary"):
st.session_state["active_page"] = "Course Details"
st.rerun()
if st.button("About This Course", use_container_width=True,
type="primary" if st.session_state["active_page"] == "About This Course" else "secondary"):
st.session_state["active_page"] = "About This Course"
st.rerun()
if st.button("What You'll Learn", use_container_width=True,
type="primary" if st.session_state["active_page"] == "What You'll Learn" else "secondary"):
st.session_state["active_page"] = "What You'll Learn"
st.rerun()
if st.button("Background Part A", use_container_width=True,
type="primary" if st.session_state["active_page"] == "Background Part A" else "secondary"):
st.session_state["active_page"] = "Background Part A"
st.rerun()
if st.button("Background Part B", use_container_width=True,
type="primary" if st.session_state["active_page"] == "Background Part B" else "secondary"):
st.session_state["active_page"] = "Background Part B"
st.rerun()
if st.button("Learning Outcomes", use_container_width=True,
type="primary" if st.session_state["active_page"] == "Learning Outcomes" else "secondary"):
st.session_state["active_page"] = "Learning Outcomes"
st.rerun()
if st.button("Instructional Methods", use_container_width=True,
type="primary" if st.session_state["active_page"] == "Instructional Methods" else "secondary"):
st.session_state["active_page"] = "Instructional Methods"
st.rerun()
if st.button("Assessment Methods", use_container_width=True,
type="primary" if st.session_state["active_page"] == "Assessment Methods" else "secondary"):
st.session_state["active_page"] = "Assessment Methods"
st.rerun()
if st.button("LU Sequencing Rationale", use_container_width=True,
type="primary" if st.session_state["active_page"] == "LU Sequencing Rationale" else "secondary"):
st.session_state["active_page"] = "LU Sequencing Rationale"
st.rerun()
if st.button("Course Validation", use_container_width=True,
type="primary" if st.session_state["active_page"] == "Course Validation" else "secondary"):
st.session_state["active_page"] = "Course Validation"
st.rerun()
st.markdown("---")
st.caption("SUBMIT CP")
if st.button("Course Outline", use_container_width=True,
type="primary" if st.session_state["active_page"] == "Course Outline" else "secondary"):
st.session_state["active_page"] = "Course Outline"
st.rerun()
if st.button("Min Entry Requirements", use_container_width=True,
type="primary" if st.session_state["active_page"] == "Min Entry Requirements" else "secondary"):
st.session_state["active_page"] = "Min Entry Requirements"
st.rerun()
if st.button("Job Roles", use_container_width=True,
type="primary" if st.session_state["active_page"] == "Job Roles" else "secondary"):
st.session_state["active_page"] = "Job Roles"
st.rerun()
if st.button("Lesson Plan", use_container_width=True,
type="primary" if st.session_state["active_page"] == "Lesson Plan" else "secondary"):
st.session_state["active_page"] = "Lesson Plan"
st.rerun()
if st.button("CP Quality Audit", use_container_width=True,
type="primary" if st.session_state["active_page"] == "CP Quality Audit" else "secondary"):
st.session_state["active_page"] = "CP Quality Audit"
st.rerun()
st.markdown("---")
st.caption("Powered by Tertiary Infotech Academy Pte Ltd")
active_page = st.session_state["active_page"]
# --- Top bar: single dark/light theme toggle, aligned to the top right ---
_top_spacer, _top_right = st.columns([8, 2])
with _top_right:
light_mode = st.toggle("☀️ Light mode", value=False, key="light_mode")
# --- Apply selected theme (dark default via config; light via CSS overrides) ---
apply_theme(light_mode)
# --- Helper: saved course details from session state ---
saved_title = st.session_state.get("saved_course_title", "")
saved_topics = st.session_state.get("saved_course_topics", "")
has_course_details = bool(saved_title and saved_topics)
# ============================================================
# PAGE: Course Details
# ============================================================
if active_page == "Course Details":
st.header("Course Details")
st.markdown("Enter the course title and topics. This information will be used across all Prepare CP pages.")
# --- Show import summary (after a successful import + rerun) ---
if st.session_state.get("cp_import_summary"):
st.success(
"Imported from CP — populated: "
+ ", ".join(st.session_state.pop("cp_import_summary"))
)
# --- Upload an existing CP to auto-fill every page ---
with st.expander("📥 Upload existing CP to auto-fill all pages", expanded=False):
st.markdown(
"Upload an existing Course Proposal Excel file to automatically "
"populate **every page** — course details, topics, durations, methods, "
"About, What You'll Learn, Background, instruction/assessment method "
"elaborations and the Course Outline. "
"Minimum Entry Requirements and Job Roles aren't stored in the CP, "
"so they can be generated with AI."
)
cp_import_file = st.file_uploader(
"Upload CP Excel file", type=["xlsx"],
help="Select the .xlsx Course Proposal file to import",
key="cd_cp_import",
)
auto_mer_jr = st.checkbox(
"Also auto-generate Minimum Entry Requirements & Job Roles with AI",
value=True, key="cd_cp_import_mer_jr",
)
if cp_import_file is not None:
st.success(
f"**{cp_import_file.name}** uploaded "
f"({cp_import_file.size / 1024:.0f} KB)"
)
if st.button(
"Import & Auto-fill",
type="primary",
use_container_width=True,
key="cd_cp_import_btn",
):
imported = None
with st.spinner("Extracting CP and populating all pages..."):
try:
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = Path(tmp_dir) / cp_import_file.name
tmp_path.write_bytes(cp_import_file.getvalue())
imported_data = extract_data(tmp_path)
imported = populate_session_from_cp(imported_data)
except Exception as e:
st.error(f"Failed to import CP: {e}")
if imported is not None:
title = st.session_state.get("saved_course_title", "")
topics = st.session_state.get("saved_course_topics", "")
if auto_mer_jr and title and topics:
with st.spinner("Generating Minimum Entry Requirements..."):
try:
st.session_state["mer_text"] = generate_minimum_entry_requirement(
title, topics,
prompt_template=st.session_state.get("mer_prompt"),
)
imported.append("Min Entry Requirements")
except Exception as e:
st.warning(f"Could not generate Min Entry Requirements: {e}")
with st.spinner("Generating Job Roles..."):
try:
st.session_state["jr_text"] = generate_job_roles(
title, topics,
prompt_template=st.session_state.get("jr_prompt"),
)
imported.append("Job Roles")
except Exception as e:
st.warning(f"Could not generate Job Roles: {e}")
st.session_state["cp_import_summary"] = imported
st.rerun()
# --- Course Title (outside form) ---
if "cd_course_title" not in st.session_state:
st.session_state["cd_course_title"] = st.session_state.get("saved_course_title", "")
course_title = st.text_input(
"Course Title",
placeholder="e.g. Sales and Marketing Mastery",
key="cd_course_title",
)
# --- Suggest Course Titles with AI ---
with st.expander("Suggest Course Titles with AI", expanded=False):
st.markdown("Enter a course topic to brainstorm 20 appealing, SEO-friendly course titles.")
ct_prompt_template = st.session_state.get("ct_prompt", COURSE_TITLE_SUGGESTIONS_PROMPT_TEMPLATE)
if st.checkbox("Show Prompt Template", key="ct_show_prompt"):
ct_prompt = st.text_area(
"Edit the prompt template used for generation. "
"Use `{course}` as a placeholder for the course topic.",
value=ct_prompt_template,
height=300,
key="ct_prompt_input",
)
st.session_state["ct_prompt"] = ct_prompt
if st.button("Suggest Titles", type="primary", use_container_width=True, key="ct_suggest_btn"):
if not course_title:
st.warning("Please enter a course topic in the Course Title field first.")
else:
with st.spinner("Generating course title suggestions..."):
try:
result = generate_course_title_suggestions(
course_title,
prompt_template=st.session_state.get("ct_prompt"),
)
st.session_state["ct_suggestions"] = result
except Exception as e:
st.error(f"Failed to generate title suggestions: {e}")
if st.session_state.get("ct_suggestions"):
st.divider()
st.markdown("**Suggested Course Titles:**")
st.code(st.session_state["ct_suggestions"], language=None, wrap_lines=True)
# --- CASL-specific fields ---
if st.session_state.get("cp_mode") == "CASL":
if "cd_unique_skill_name" not in st.session_state:
_saved_usn = st.session_state.get("saved_unique_skill_name", "")
st.session_state["cd_unique_skill_name"] = (
_saved_usn if _saved_usn in UNIQUE_SKILL_NAMES_LIST else UNIQUE_SKILL_NAMES_LIST[0]
)
unique_skill_name = st.selectbox(
"Unique Skill Name",
options=UNIQUE_SKILL_NAMES_LIST,
key="cd_unique_skill_name",
)
# --- WSQ-specific fields ---
if st.session_state.get("cp_mode") == "WSQ":
col_tsc_code, col_tsc_title = st.columns(2)
with col_tsc_code:
tsc_ref_code = st.text_input(
"TSC Reference Code",
value=st.session_state.get("saved_tsc_ref_code", ""),
placeholder="e.g. TSC-2024-001",
key="cd_tsc_ref_code",
)
with col_tsc_title:
tsc_title = st.text_input(
"TSC Title",
value=st.session_state.get("saved_tsc_title", ""),
placeholder="e.g. Digital Marketing Strategy",
key="cd_tsc_title",
)
# --- Generate Topics with AI ---
if "cd_course_topics" not in st.session_state:
st.session_state["cd_course_topics"] = st.session_state.get("saved_course_topics", "")
with st.expander("Generate Topics with AI", expanded=False):
st.markdown("Auto-generate course topics based on the course title. You can edit the results afterwards.")
# Show skill description context for CASL mode
if st.session_state.get("cp_mode") == "CASL":
selected_skill = st.session_state.get("cd_unique_skill_name", "")
skill_desc_preview = SKILL_DESCRIPTIONS.get(selected_skill, "")
if skill_desc_preview:
st.info(f"**Skill:** {selected_skill}\n\n**Description:** {skill_desc_preview[:300]}{'...' if len(skill_desc_preview) > 300 else ''}")
else:
st.warning(f"No skill description found for **{selected_skill}**. Topics will be generated based on the course title only.")
saved_dur = st.session_state.get("saved_course_duration", 16)
default_days = max(1.0, float(saved_dur // 8))
num_days_est = st.number_input(
"No. of Days",
min_value=0.5,
value=default_days,
step=0.5,
format="%.1f",
key="gen_num_days",
help="Typically 2-3 topics per day",
)
special_req = st.text_area(
"Special Requirements (optional)",
value="",
height=80,
key="gen_special_req",
placeholder="e.g. Must include a topic on safety regulations, focus on hands-on practical skills, etc.",
)
max_topics = num_days_est * 3
st.caption(f"AI will generate **2-3 topics per day** for **{num_days_est} day(s)** (max {max_topics} topics)")
if st.button("Generate Topics", type="primary", use_container_width=True, key="gen_topics_btn"):
if not course_title:
st.warning("Please enter a course title first.")
else:
with st.spinner("Generating course topics..."):
try:
# In CASL mode, look up the skill description for context
skill_desc = ""
if st.session_state.get("cp_mode") == "CASL":
selected_skill = st.session_state.get("cd_unique_skill_name", "")
skill_desc = SKILL_DESCRIPTIONS.get(selected_skill, "")
result = generate_course_topics(
course_title, num_days_est,
skill_description=skill_desc,
special_requirements=special_req,
)
st.session_state["cd_course_topics"] = result
# Auto-detect actual topic count from generated result
generated_count = len(re.findall(r"^##\s*Topic\s*\d+", result, re.MULTILINE))
if generated_count > 0:
st.session_state["saved_num_topics"] = generated_count
st.rerun()
except Exception as e:
st.error(f"Failed to generate topics: {e}")
# --- Course Topics (outside form, editable) ---
course_topics = st.text_area(
"Course Topics",
placeholder=(
"## Topic 1: Strategic Marketing Principles\n"
"- Explain core marketing frameworks and models\n"
"- Identify target market segments and positioning strategies\n\n"
"## Topic 2: Consumer Behaviour Analysis\n"
"- Describe consumer decision-making processes\n"
"- Analyse factors influencing purchasing behaviour"
),
height=400,
key="cd_course_topics",
)
if course_topics:
with st.expander("Preview", expanded=False):
st.markdown(course_topics)
# --- Rest of settings in form ---
with st.form("course_details_form"):
col_dur, col_topics = st.columns(2)
with col_dur:
course_duration = st.number_input(
"Course Duration (hrs)",
min_value=1,
value=st.session_state.get("saved_course_duration", 16),
step=1,
)
with col_topics:
num_topics = st.number_input(
"No. of Topics",
min_value=1,
value=st.session_state.get("saved_num_topics", 4),
step=1,
)
is_casl = st.session_state.get("cp_mode") == "CASL"
col_instr, col_assess = st.columns(2)
with col_instr:
instructional_duration = st.number_input(
"Instructional Duration (hrs)",
min_value=1,
value=st.session_state.get("saved_instructional_duration", 14),
step=1,
)
with col_assess:
assessment_duration = st.number_input(
"Assessment Duration (hrs)",
min_value=0 if is_casl else 1,
value=st.session_state.get("saved_assessment_duration", 0 if is_casl else 2),
step=1,
)
col_num_instr, col_num_assess = st.columns(2)
with col_num_instr:
num_instr_methods = st.number_input(
"No. of Instructional Methods",
min_value=1,
value=st.session_state.get("saved_num_instr_methods", 3),
step=1,
)
with col_num_assess:
num_assess_methods = st.number_input(
"No. of Assessment Methods",
min_value=0 if is_casl else 1,
value=st.session_state.get("saved_num_assess_methods", 0 if is_casl else 2),
step=1,
)
selected_instr_methods = st.multiselect(
"Select Instructional Methods",
options=INSTRUCTION_METHODS_LIST,
default=st.session_state.get("saved_instr_methods", [
"Interactive presentation", "Discussions", "Case studies",
]),
)
selected_assess_methods = st.multiselect(
"Select Assessment Methods",
options=ASSESSMENT_METHODS_LIST,
default=st.session_state.get("saved_assess_methods", [
"Written Exam", "Practical Exam",
]),
)
submitted = st.form_submit_button("Save Course Details", type="primary", use_container_width=True)
if submitted:
if not course_title or not course_topics:
st.warning("Please enter both a course title and course topics.")
elif len(selected_instr_methods) != num_instr_methods:
st.warning(f"Please select exactly {num_instr_methods} instruction method(s). You selected {len(selected_instr_methods)}.")
elif num_assess_methods > 0 and len(selected_assess_methods) != num_assess_methods:
st.warning(f"Please select exactly {num_assess_methods} assessment method(s). You selected {len(selected_assess_methods)}.")
else:
st.session_state["saved_course_title"] = course_title
st.session_state["saved_course_topics"] = course_topics
st.session_state["saved_course_duration"] = course_duration
st.session_state["saved_num_topics"] = num_topics
st.session_state["saved_instructional_duration"] = instructional_duration
st.session_state["saved_assessment_duration"] = assessment_duration
st.session_state["saved_num_instr_methods"] = num_instr_methods
st.session_state["saved_num_assess_methods"] = num_assess_methods
st.session_state["saved_instr_methods"] = selected_instr_methods
st.session_state["saved_assess_methods"] = selected_assess_methods if num_assess_methods > 0 else []
if st.session_state.get("cp_mode") == "CASL":
st.session_state["saved_unique_skill_name"] = unique_skill_name
if st.session_state.get("cp_mode") == "WSQ":
st.session_state["saved_tsc_ref_code"] = tsc_ref_code
st.session_state["saved_tsc_title"] = tsc_title
st.rerun()
# --- Show saved details ---
if has_course_details:
saved_duration = st.session_state.get("saved_course_duration", 8)
saved_num_topics = st.session_state.get("saved_num_topics", 3)
saved_instr = st.session_state.get("saved_instructional_duration", 7)
saved_assess = st.session_state.get("saved_assessment_duration", 1)
saved_num_instr = st.session_state.get("saved_num_instr_methods", 3)
saved_num_assess = st.session_state.get("saved_num_assess_methods", 1)
duration_per_topic = saved_duration * 60 / saved_num_topics
instr_per_topic = saved_instr * 60 / saved_num_topics
assess_per_topic = saved_assess * 60 / saved_num_topics
import math
num_days = max(1, saved_duration / 8)
calendar_days = math.ceil(num_days)
instr_per_method_per_day = saved_instr * 60 / calendar_days / saved_num_instr
assess_per_method = saved_assess * 60 / saved_num_assess if saved_num_assess > 0 else 0
st.divider()
st.markdown(f"## {saved_title}")
summary_data = {
"Field": [
"Total Course Duration",
"Number of Topics",
"Duration per Topic",
"Instructional Duration",
"Instructional per Topic",
"No. of Instructional Methods",
"Duration per Instructional Method per Day",
"Assessment Duration",
"No. of Assessment Methods",
"Duration per Assessment Method",
],
"Value": [
f"{saved_duration * 60:.0f} mins",
str(saved_num_topics),
f"{duration_per_topic:.0f} mins",
f"{saved_instr} hrs",
f"{instr_per_topic:.0f} mins",
str(saved_num_instr),
f"{instr_per_method_per_day:.0f} mins",
f"{saved_assess} hrs" if saved_num_assess > 0 else "N/A",
str(saved_num_assess),
f"{assess_per_method:.0f} mins" if saved_num_assess > 0 else "N/A",
],
}
st.dataframe(summary_data, use_container_width=True, hide_index=True)
# ============================================================
# PAGE: About This Course
# ============================================================
elif active_page == "About This Course":
st.header("About This Course")
if not has_course_details:
st.warning("Please enter course details first on the **Course Details** page.")
else:
st.info(f"**Course:** {saved_title}")
st.markdown(
"AI will generate a professional \"About the Course\" description "
"suitable for course listings."
)
# --- Editable prompt template ---
with st.expander("Prompt Template", expanded=False):
about_prompt = st.text_area(
"Edit the prompt template used for generation. "
"Use `{course_title}` and `{course_topics}` as placeholders.",
value=st.session_state.get("about_prompt", ABOUT_COURSE_PROMPT_TEMPLATE),
height=300,
key="about_prompt_input",
)
st.session_state["about_prompt"] = about_prompt
# --- Generate Buttons ---
col_gen, col_regen = st.columns([1, 1])
with col_gen:
generate_clicked = st.button(
"Generate",
type="primary",
use_container_width=True,
key="about_gen",
)
with col_regen:
regenerate_clicked = st.button(
"Regenerate",
use_container_width=True,
key="about_regen",
)
# --- Generation Logic ---
if generate_clicked or regenerate_clicked:
if not has_course_details:
st.warning("Please enter course details first on the **Course Details** page.")
else:
with st.spinner("Generating description..."):
try:
result = generate_about_course(
saved_title, saved_topics,
prompt_template=st.session_state.get("about_prompt"),
)
st.session_state["about_course_text"] = result
except Exception as e:
st.error(f"Failed to generate text: {e}")
# --- Display Result ---
if st.session_state.get("about_course_text"):
st.divider()
st.markdown("**Generated \"About the Course\" Text:**")
st.code(st.session_state["about_course_text"], language=None, wrap_lines=True)
# ============================================================
# PAGE: What You'll Learn
# ============================================================
elif active_page == "What You'll Learn":
st.header("What You'll Learn")
if not has_course_details:
st.warning("Please enter course details first on the **Course Details** page.")
else:
st.info(f"**Course:** {saved_title}")
st.markdown(
"AI will generate learning outcomes describing the skills and knowledge "
"trainees will gain from the course."
)
# --- Editable prompt template ---
with st.expander("Prompt Template", expanded=False):
wyl_prompt = st.text_area(
"Edit the prompt template used for generation. "
"Use `{course_title}` and `{course_topics}` as placeholders.",
value=st.session_state.get("wyl_prompt", WHAT_YOULL_LEARN_PROMPT_TEMPLATE),
height=300,
key="wyl_prompt_input",
)
st.session_state["wyl_prompt"] = wyl_prompt
# --- Generate Buttons ---
col_gen, col_regen = st.columns([1, 1])
with col_gen:
wyl_generate = st.button(
"Generate",
type="primary",
use_container_width=True,
key="wyl_gen",
)
with col_regen:
wyl_regenerate = st.button(
"Regenerate",
use_container_width=True,
key="wyl_regen",
)
# --- Generation Logic ---
if wyl_generate or wyl_regenerate:
if not has_course_details:
st.warning("Please enter course details first on the **Course Details** page.")
else:
with st.spinner("Generating learning outcomes..."):
try:
result = generate_what_youll_learn(
saved_title, saved_topics,
prompt_template=st.session_state.get("wyl_prompt"),
)
st.session_state["wyl_text"] = result
except Exception as e:
st.error(f"Failed to generate text: {e}")
# --- Display Result ---
if st.session_state.get("wyl_text"):
st.divider()
st.markdown("**Generated \"What You'll Learn\" Text:**")
st.code(st.session_state["wyl_text"], language=None, wrap_lines=True)
# ============================================================
# PAGE: Background Part A
# ============================================================
elif active_page == "Background Part A":
st.header("Background Part A")
if not has_course_details:
st.warning("Please enter course details first on the **Course Details** page.")
else:
st.info(f"**Course:** {saved_title}")
st.markdown(
"AI will generate a background section covering targeted sector(s), "
"target audience / job role(s), and needs for the training."
)
# --- Editable prompt template ---
with st.expander("Prompt Template", expanded=False):
bg_prompt = st.text_area(
"Edit the prompt template used for generation. "
"Use `{course_title}` and `{course_topics}` as placeholders.",
value=st.session_state.get("bg_prompt", BACKGROUND_PART_A_PROMPT_TEMPLATE),
height=300,
key="bg_prompt_input",
)
st.session_state["bg_prompt"] = bg_prompt
# --- Generate Buttons ---
col_gen, col_regen = st.columns([1, 1])
with col_gen:
bg_generate = st.button(
"Generate",
type="primary",
use_container_width=True,
key="bg_gen",
)
with col_regen:
bg_regenerate = st.button(
"Regenerate",
use_container_width=True,
key="bg_regen",
)
# --- Generation Logic ---
if bg_generate or bg_regenerate:
if not has_course_details:
st.warning("Please enter course details first on the **Course Details** page.")
else:
with st.spinner("Generating background section..."):
try:
result = generate_background_part_a(
saved_title, saved_topics,
prompt_template=st.session_state.get("bg_prompt"),
)
st.session_state["bg_text"] = result
except Exception as e:
st.error(f"Failed to generate text: {e}")
# --- Display Result ---
if st.session_state.get("bg_text"):
st.divider()
st.markdown("**Generated \"Background Part A\" Text:**")
st.code(st.session_state["bg_text"], language=None, wrap_lines=True)
# ============================================================
# PAGE: Background Part B
# ============================================================
elif active_page == "Background Part B":
st.header("Background Part B")
if not has_course_details:
st.warning("Please enter course details first on the **Course Details** page.")
else:
st.info(f"**Course:** {saved_title}")
st.markdown(
"AI will generate a section covering performance gaps the course addresses, "
"how the gaps were identified, and how learners will benefit post-training."
)
# --- Editable prompt template ---
with st.expander("Prompt Template", expanded=False):
bgb_prompt = st.text_area(
"Edit the prompt template used for generation. "
"Use `{course_title}` and `{course_topics}` as placeholders.",
value=st.session_state.get("bgb_prompt", BACKGROUND_PART_B_PROMPT_TEMPLATE),
height=300,
key="bgb_prompt_input",
)
st.session_state["bgb_prompt"] = bgb_prompt
# --- Generate Buttons ---
col_gen, col_regen = st.columns([1, 1])
with col_gen:
bgb_generate = st.button(
"Generate",
type="primary",
use_container_width=True,
key="bgb_gen",
)
with col_regen:
bgb_regenerate = st.button(
"Regenerate",
use_container_width=True,
key="bgb_regen",
)
# --- Generation Logic ---
if bgb_generate or bgb_regenerate:
if not has_course_details:
st.warning("Please enter course details first on the **Course Details** page.")
else:
with st.spinner("Generating performance gaps section..."):
try:
result = generate_background_part_b(
saved_title, saved_topics,
prompt_template=st.session_state.get("bgb_prompt"),
)
st.session_state["bgb_text"] = result
except Exception as e:
st.error(f"Failed to generate text: {e}")
# --- Display Result ---
if st.session_state.get("bgb_text"):
st.divider()
st.markdown("**Generated \"Background Part B\" Text:**")
st.code(st.session_state["bgb_text"], language=None, wrap_lines=True)
# ============================================================
# PAGE: Learning Outcomes
# ============================================================
elif active_page == "Learning Outcomes":
st.header("Learning Outcomes")
if not has_course_details:
st.warning("Please enter course details first on the **Course Details** page.")
else:
st.info(f"**Course:** {saved_title}")
st.markdown(
"AI will generate learning outcomes for each topic. "
"Each outcome starts with an action verb and is under 25 words."
)
# --- Editable prompt template ---
with st.expander("Prompt Template", expanded=False):
lo_prompt = st.text_area(
"Edit the prompt template used for generation. "
"Use `{course_title}` and `{course_topics}` as placeholders.",
value=st.session_state.get("lo_prompt", LEARNING_OUTCOME_PROMPT_TEMPLATE),
height=300,
key="lo_prompt_input",
)
st.session_state["lo_prompt"] = lo_prompt
# --- Generate Buttons ---
col_gen, col_regen = st.columns([1, 1])
with col_gen:
lo_generate = st.button(
"Generate",
type="primary",
use_container_width=True,
key="lo_gen",
)
with col_regen:
lo_regenerate = st.button(
"Regenerate",
use_container_width=True,
key="lo_regen",
)
# --- Generation Logic ---
if lo_generate or lo_regenerate:
if not has_course_details:
st.warning("Please enter course details first on the **Course Details** page.")
else:
with st.spinner("Generating learning outcomes..."):
try:
result = generate_learning_outcomes(