cryogenic22 commited on
Commit
37569f6
·
verified ·
1 Parent(s): 9ecccaf

Create utils/learning_module.py

Browse files
Files changed (1) hide show
  1. utils/learning_module.py +261 -0
utils/learning_module.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # utils/learning_module.py
2
+
3
+ from datetime import datetime
4
+ import json
5
+ from pathlib import Path
6
+ import streamlit as st
7
+ import base64
8
+ from PIL import Image
9
+ import io
10
+
11
+ TRADING_COURSES = {
12
+ "Trading 101": {
13
+ "title": "Introduction to Trading",
14
+ "description": "Foundation course for beginners",
15
+ "modules": [
16
+ {
17
+ "title": "Understanding Markets",
18
+ "topics": [
19
+ {"name": "What are Financial Markets", "requires_visuals": True},
20
+ {"name": "Types of Markets (Stocks, Forex, Crypto)", "requires_visuals": True},
21
+ {"name": "Market Participants", "requires_visuals": False},
22
+ {"name": "Basic Market Mechanics", "requires_visuals": True}
23
+ ]
24
+ },
25
+ {
26
+ "title": "Trading Basics",
27
+ "topics": [
28
+ {"name": "What is Trading", "requires_visuals": False},
29
+ {"name": "Different Trading Styles", "requires_visuals": False},
30
+ {"name": "Basic Chart Reading", "requires_visuals": True},
31
+ {"name": "Understanding Price Action", "requires_visuals": True}
32
+ ]
33
+ },
34
+ {
35
+ "title": "Risk Management",
36
+ "topics": [
37
+ {"name": "Importance of Risk Management", "requires_visuals": True},
38
+ {"name": "Position Sizing", "requires_visuals": True},
39
+ {"name": "Stop Loss Basics", "requires_visuals": True},
40
+ {"name": "Risk-Reward Ratio", "requires_visuals": True}
41
+ ]
42
+ }
43
+ ]
44
+ },
45
+ # Similar structure for Trading 201 and 301...
46
+ }
47
+
48
+ class LearningContent:
49
+ def __init__(self, text_content, diagrams=None, examples=None):
50
+ self.text_content = text_content
51
+ self.diagrams = diagrams or []
52
+ self.examples = examples or []
53
+
54
+ class LearningModule:
55
+ def __init__(self, claude_service):
56
+ self.claude_service = claude_service
57
+ self.data_dir = Path("data")
58
+ self.learning_dir = self.data_dir / "learning"
59
+ self.content_dir = self.learning_dir / "content"
60
+ self.images_dir = self.learning_dir / "images"
61
+ self.setup_directories()
62
+
63
+ def setup_directories(self):
64
+ """Create necessary directories"""
65
+ for directory in [self.data_dir, self.learning_dir, self.content_dir, self.images_dir]:
66
+ directory.mkdir(parents=True, exist_ok=True)
67
+
68
+ def get_diagram_prompt(self, topic, concept):
69
+ """Create a prompt for generating a diagram"""
70
+ return f"""Create a clear, educational diagram to explain '{concept}' for {topic}.
71
+ Make the diagram simple yet informative, suitable for learning purposes.
72
+ Focus on key visual elements that help explain the concept.
73
+ Use clear labels and annotations.
74
+ Include a brief title and legend if necessary."""
75
+
76
+ def get_course_content(self, course_name, topic_data):
77
+ """Get or generate detailed content for a specific topic"""
78
+ topic = topic_data["name"]
79
+ try:
80
+ # Create unique identifier for content
81
+ content_id = f"{course_name}_{topic}".replace(" ", "_").lower()
82
+ content_file = self.content_dir / f"{content_id}.json"
83
+
84
+ # Check if content is cached
85
+ if content_file.exists():
86
+ with open(content_file, 'r') as f:
87
+ stored_content = json.load(f)
88
+ return LearningContent(**stored_content)
89
+
90
+ # Generate new content
91
+ base_prompt = f"""Create a comprehensive lesson for the topic '{topic}' in the {course_name} course.
92
+ Structure the content as follows:
93
+ 1. Overview
94
+ 2. Key Concepts
95
+ 3. Practical Examples
96
+ 4. Common Mistakes to Avoid
97
+ 5. Practice Exercises
98
+ 6. Additional Resources
99
+
100
+ Make this suitable for the course level:
101
+ - Trading 101: Basic concepts, simple language
102
+ - Trading 201: Intermediate concepts, some technical terms
103
+ - Trading 301: Advanced concepts, technical language
104
+ """
105
+
106
+ text_content = self.claude_service.generate_educational_content(base_prompt)
107
+ diagrams = []
108
+ examples = []
109
+
110
+ # Generate diagrams if needed
111
+ if topic_data.get("requires_visuals", False):
112
+ # Extract key concepts for visualization
113
+ concepts_prompt = f"List the 3 most important concepts from '{topic}' that would benefit from visual representation."
114
+ concepts = self.claude_service.generate_educational_content(concepts_prompt).split('\n')
115
+
116
+ for concept in concepts:
117
+ # Generate diagram for each concept
118
+ diagram_prompt = self.get_diagram_prompt(topic, concept)
119
+ diagram = self.claude_service.generate_diagram(diagram_prompt)
120
+
121
+ if diagram:
122
+ # Save diagram
123
+ diagram_filename = f"{content_id}_{len(diagrams)}.svg"
124
+ diagram_path = self.images_dir / diagram_filename
125
+ with open(diagram_path, 'w') as f:
126
+ f.write(diagram)
127
+ diagrams.append(diagram_filename)
128
+
129
+ # Generate an example using the diagram
130
+ example_prompt = f"Create a practical example explaining {concept} using the diagram."
131
+ example = self.claude_service.generate_educational_content(example_prompt)
132
+ examples.append({
133
+ 'concept': concept,
134
+ 'example': example,
135
+ 'diagram': diagram_filename
136
+ })
137
+
138
+ # Create and cache content
139
+ content = LearningContent(
140
+ text_content=text_content,
141
+ diagrams=diagrams,
142
+ examples=examples
143
+ )
144
+
145
+ with open(content_file, 'w') as f:
146
+ json.dump(vars(content), f)
147
+
148
+ return content
149
+
150
+ except Exception as e:
151
+ st.error(f"Error generating course content: {str(e)}")
152
+ return None
153
+
154
+ def display_content(self, content):
155
+ """Display multi-modal content in the UI"""
156
+ if not content:
157
+ return
158
+
159
+ # Display main content
160
+ st.markdown(content.text_content)
161
+
162
+ # Display examples with diagrams
163
+ if content.examples:
164
+ st.subheader("Interactive Examples")
165
+ for example in content.examples:
166
+ with st.expander(f"Example: {example['concept']}"):
167
+ # Display diagram
168
+ diagram_path = self.images_dir / example['diagram']
169
+ if diagram_path.exists():
170
+ with open(diagram_path, 'r') as f:
171
+ svg_content = f.read()
172
+ st.image(svg_content, use_container_width=True)
173
+
174
+ # Display explanation
175
+ st.markdown(example['example'])
176
+
177
+ # Add interactive elements
178
+ st.markdown("---")
179
+ st.write("Try it yourself:")
180
+ user_input = st.text_area("Practice your understanding:", key=f"practice_{example['concept']}")
181
+ if st.button("Check Understanding", key=f"check_{example['concept']}"):
182
+ feedback = self.claude_service.generate_educational_content(
183
+ f"Provide constructive feedback on this understanding of {example['concept']}: {user_input}"
184
+ )
185
+ st.write(feedback)
186
+
187
+ def display_course_selection(self):
188
+ """Display course selection interface"""
189
+ st.subheader("Trading Courses")
190
+
191
+ # Course selection
192
+ selected_course = st.selectbox(
193
+ "Select a Course",
194
+ list(TRADING_COURSES.keys()),
195
+ key="course_selector"
196
+ )
197
+
198
+ course_data = TRADING_COURSES[selected_course]
199
+ st.write(course_data["description"])
200
+
201
+ # Module selection
202
+ selected_module = st.selectbox(
203
+ "Select a Module",
204
+ [module["title"] for module in course_data["modules"]],
205
+ key="module_selector"
206
+ )
207
+
208
+ # Find selected module data
209
+ module_data = next(m for m in course_data["modules"] if m["title"] == selected_module)
210
+
211
+ # Topic selection
212
+ selected_topic_name = st.selectbox(
213
+ "Select a Topic",
214
+ [topic["name"] for topic in module_data["topics"]],
215
+ key="topic_selector"
216
+ )
217
+
218
+ selected_topic = next(t for t in module_data["topics"] if t["name"] == selected_topic_name)
219
+
220
+ if st.button("Start Learning", key="start_learning"):
221
+ with st.spinner("Loading content..."):
222
+ content = self.get_course_content(selected_course, selected_topic)
223
+ if content:
224
+ self.display_content(content)
225
+
226
+ def display_custom_learning(self):
227
+ """Display custom learning interface"""
228
+ st.subheader("Ask Any Trading Question")
229
+ question = st.text_input(
230
+ "What would you like to learn about?",
231
+ key="custom_question"
232
+ )
233
+
234
+ needs_visual = st.checkbox("Include visual explanation", value=True)
235
+
236
+ if st.button("Get Answer", key="custom_answer"):
237
+ if question:
238
+ with st.spinner("Generating response..."):
239
+ # Generate text response
240
+ response = self.claude_service.generate_educational_content(question)
241
+
242
+ if needs_visual:
243
+ # Generate diagram
244
+ diagram = self.claude_service.generate_diagram(
245
+ self.get_diagram_prompt("Custom Learning", question)
246
+ )
247
+
248
+ if diagram:
249
+ # Save diagram
250
+ diagram_filename = f"custom_{datetime.now().strftime('%Y%m%d_%H%M%S')}.svg"
251
+ diagram_path = self.images_dir / diagram_filename
252
+ with open(diagram_path, 'w') as f:
253
+ f.write(diagram)
254
+
255
+ # Display content
256
+ st.markdown(response)
257
+ with open(diagram_path, 'r') as f:
258
+ svg_content = f.read()
259
+ st.image(svg_content, use_container_width=True)
260
+ else:
261
+ st.markdown(response)