NSamson1 commited on
Commit
2f92028
Β·
verified Β·
1 Parent(s): a37c208

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +203 -199
src/streamlit_app.py CHANGED
@@ -9,7 +9,7 @@ import time
9
  import tempfile
10
 
11
  # Page config
12
- st.set_page_config(page_title="πŸŽ“ Smart Math Teacher", layout="centered")
13
 
14
  # Custom CSS with beautiful colors and stable layout
15
  st.markdown("""
@@ -106,238 +106,242 @@ st.markdown("""
106
  .main-content {
107
  min-height: 100vh;
108
  }
 
 
 
 
 
 
109
  </style>
110
  """, unsafe_allow_html=True)
111
 
112
- # Welcome title
113
- st.markdown("<div class='fun-title'>🧠✨ Welcome to the Smart Math Teacher! ✨🧠</div>", unsafe_allow_html=True)
114
-
115
- # USER GUIDE SECTION
116
- with st.expander("πŸ“– **How to Use This App - Click to Expand Guide**", expanded=True):
117
- st.markdown("""
118
- <div class="guide-box">
119
- <h3>🎯 Quick Start Guide:</h3>
120
-
121
- **Step 1: Choose Your Level** πŸ‘‡
122
- - Select your age group from the dropdown
123
- - 4-6: Basic counting and simple math
124
- - 7-9: Addition, subtraction, multiplication
125
- - 13-15: Advanced math and algebra
126
-
127
- **Step 2: Pick a Category** πŸ“š
128
- - Choose what type of math you want to practice
129
- - Each category has different types of questions
130
-
131
- **Step 3: Solve Problems** ✏️
132
- - Read each question carefully
133
- - Type your answer in the box
134
- - Click "Submit Answer" to check
135
-
136
- **Step 4: Get Help When Needed** πŸ’‘
137
- - Use "Show Hint" if you're stuck
138
- - "Show Steps" explains how to solve it
139
- - "Skip" moves to the next question
140
-
141
- **Tips for Success:** 🌟
142
- - Take your time with each problem
143
- - Don't worry about mistakes - they help you learn!
144
- - Practice regularly to improve your skills
145
- </div>
146
- """, unsafe_allow_html=True)
147
-
148
  # Initialize session state for temp directory
149
  if 'temp_dir' not in st.session_state:
150
  st.session_state.temp_dir = tempfile.mkdtemp()
151
 
152
- # Age group setup
153
- age_groups = {
154
- "4-6 Age Group": {"dataset": "src/Datase_of_4-6_Age_Group.xlsx", "zip_file": "src/Image_for_group_4-6.zip", "image_folder": "Image_for_group_4-6"},
155
- "7-9 Age Group": {"dataset": "src/Datase_of_7-9_Age_Group.xlsx", "zip_file": "src/Image_for_group_7-9.zip", "image_folder": "Image_for_group_7-9"},
156
- "13-15 Age Group": {"dataset": "src/Datase_of_13-15_Age_Group.xlsx", "zip_file": "src/Image_for_group_13-15.zip", "image_folder": "Image_for_group_13-15"},
157
- }
158
 
159
- # Age group selection with better layout
160
- st.markdown("---")
161
- st.markdown("### πŸ§’ Select Your Learning Level")
162
- selected_age_group = st.selectbox(
163
- "Choose your age group:",
164
- list(age_groups.keys()),
165
- key="age_group_selector"
166
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
 
168
- # Age group descriptions
169
- age_descriptions = {
170
- "4-6 Age Group": "🎨 **Fun with Numbers**: Counting, shapes, and basic addition",
171
- "7-9 Age Group": "πŸš€ **Math Adventures**: Addition, subtraction, multiplication",
172
- "13-15 Age Group": "🌟 **Math Master**: Algebra, geometry, and problem solving"
173
- }
 
 
174
 
175
- st.info(age_descriptions[selected_age_group])
 
 
 
 
 
176
 
177
- # Initialize session
178
- if "session_initialized" not in st.session_state or st.session_state.age_group != selected_age_group:
179
- st.session_state.age_group = selected_age_group
180
- st.session_state.category = None
181
- st.session_state.question_index = 0
182
- st.session_state.show_answer = False
183
- st.session_state.show_steps = False
184
- st.session_state.session_initialized = True
185
 
186
- # Load dataset
187
- group_info = age_groups[selected_age_group]
188
- dataset_path = group_info["dataset"]
189
- zip_path = group_info["zip_file"]
190
- image_folder = group_info["image_folder"]
191
 
192
- # Create image folder in temp directory
193
- temp_image_folder = os.path.join(st.session_state.temp_dir, image_folder)
194
- os.makedirs(temp_image_folder, exist_ok=True)
 
 
 
 
 
195
 
196
- # Extract images if zip exists
197
- try:
198
- if os.path.exists(zip_path):
199
- with zipfile.ZipFile(zip_path, "r") as zip_ref:
200
- zip_ref.extractall(temp_image_folder)
201
- except Exception as e:
202
- st.warning(f"Error extracting images: {e}")
203
 
204
- if not os.path.exists(dataset_path):
205
- st.error(f"Dataset not found: {dataset_path}")
206
- st.stop()
207
 
208
- try:
209
- df = pd.read_excel(dataset_path)
210
- df['category'] = df['category'].astype(str).str.strip()
211
- except Exception as e:
212
- st.error(f"Error loading dataset: {e}")
213
- st.stop()
 
214
 
215
- # Category selection
216
- st.markdown("---")
217
- st.markdown("### πŸ“š Choose Your Math Category")
218
- categories = sorted(df['category'].dropna().unique())
219
- selected_category = st.selectbox(
220
- "Select a category to practice:",
221
- options=categories,
222
- key="category_selector"
223
- )
224
 
225
- # Update session if category changes
226
- if st.session_state.category != selected_category:
227
- st.session_state.category = selected_category
228
- st.session_state.question_index = 0
229
- st.session_state.show_answer = False
230
- st.session_state.show_steps = False
231
- st.rerun()
232
 
233
- # Filter questions by selected category only
234
- subset_df = df[df['category'] == selected_category].reset_index(drop=True)
 
 
 
 
 
 
235
 
236
- # MAIN CONTENT AREA
237
- st.markdown("---")
 
 
 
 
 
238
 
239
- if not subset_df.empty and st.session_state.question_index < len(subset_df):
240
- question = subset_df.iloc[st.session_state.question_index]
241
- progress = int((st.session_state.question_index / len(subset_df)) * 100)
242
-
243
- # Progress information
244
- col_progress1, col_progress2 = st.columns([3, 1])
245
- with col_progress1:
246
- st.progress(progress)
247
- with col_progress2:
248
- st.write(f"**{st.session_state.question_index + 1} of {len(subset_df)}**")
249
 
250
- st.markdown(f"<div class='question-box'>πŸ“˜ <b>Question {st.session_state.question_index + 1}:</b><br><br>{question['problem']}</div>", unsafe_allow_html=True)
 
251
 
252
- # Display image with error handling
253
- if pd.notna(question.get('image')):
254
- image_name = str(question['image']).strip()
255
- image_found = False
256
- for root, _, files in os.walk(temp_image_folder):
257
- for file in files:
258
- if file.lower().startswith(image_name.lower()) or os.path.splitext(file)[0].lower() == image_name.lower():
259
- try:
260
- st.image(Image.open(os.path.join(root, file)), use_column_width=True)
261
- image_found = True
262
- break
263
- except:
264
- pass
265
- if not image_found:
266
- st.warning("❌ Image not found for this question.")
267
 
268
- # Answer section
269
- st.markdown("### ✏️ Your Turn to Solve!")
270
- user_ans = st.text_input("Type your answer below:", key=f"ans_{st.session_state.question_index}")
271
 
272
- # Action buttons in columns
273
- col1, col2, col3 = st.columns(3)
274
-
275
- with col1:
276
- if st.button("βœ… Submit Answer", use_container_width=True):
277
- if str(user_ans).strip().lower() == str(question['answer']).strip().lower():
278
- st.success("πŸŽ‰ Correct! Well done!")
279
- st.balloons()
280
- time.sleep(2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  st.session_state.question_index += 1
282
  st.session_state.show_answer = False
283
  st.session_state.show_steps = False
284
  st.rerun()
285
- else:
286
- st.error("❌ Not quite right. Try again or use the hint below!")
287
- st.session_state.show_answer = True
288
- st.session_state.show_steps = False
289
 
290
- with col2:
291
- if st.button("πŸ’‘ Show Hint", use_container_width=True):
292
- st.session_state.show_answer = True
293
- st.session_state.show_steps = False
294
- st.info("πŸ’‘ Need help? Check the answer below!")
 
 
 
 
 
 
 
295
 
296
- with col3:
297
- if st.button("⏭️ Skip Question", use_container_width=True):
298
- st.session_state.question_index += 1
299
- st.session_state.show_answer = False
300
- st.session_state.show_steps = False
301
- st.rerun()
302
-
303
- # Help sections
304
- if st.session_state.show_answer:
305
  st.markdown("---")
306
- st.markdown("### πŸ’‘ Need Help?")
307
- st.info(f"**βœ… Correct Answer:** **{question['answer']}**")
308
 
309
- if selected_age_group in ["7-9 Age Group", "13-15 Age Group"]:
310
- if st.button("πŸ” Show Step-by-Step Solution"):
311
- st.session_state.show_steps = True
312
 
313
- if st.session_state.show_steps and pd.notna(question.get("steps", None)):
314
- st.success(f"### πŸͺ„ How to Solve:\n{question['steps']}")
315
-
316
- elif subset_df.empty:
317
- st.warning("⚠️ No questions available in this category. Please try another category!")
318
- else:
319
- st.markdown("---")
320
- st.success("""
321
- # πŸ† Congratulations!
322
-
323
- ### You've completed all questions in this category!
324
-
325
- πŸŽ‰ **Great job!** You're becoming a math superstar!
326
-
327
- **What to do next:**
328
- - Try another category in the same age group
329
- - Move to a more challenging age group
330
- - Practice regularly to keep improving!
331
- """)
332
- st.balloons()
333
-
334
- # Footer with tips
335
- st.markdown("---")
336
- st.markdown("""
337
- <div style='text-align: center; color: #666; font-size: 14px;'>
338
- πŸ’‘ <b>Tip:</b> The page might scroll when changing groups - this is normal! Just scroll down to continue learning.
339
- </div>
340
- """, unsafe_allow_html=True)
341
 
342
  # Cleanup function
343
  def cleanup():
 
9
  import tempfile
10
 
11
  # Page config
12
+ st.set_page_config(page_title="πŸŽ“ Smart Math Teacher", layout="wide")
13
 
14
  # Custom CSS with beautiful colors and stable layout
15
  st.markdown("""
 
106
  .main-content {
107
  min-height: 100vh;
108
  }
109
+
110
+ /* Sidebar styling */
111
+ .sidebar-content {
112
+ position: sticky;
113
+ top: 20px;
114
+ }
115
  </style>
116
  """, unsafe_allow_html=True)
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  # Initialize session state for temp directory
119
  if 'temp_dir' not in st.session_state:
120
  st.session_state.temp_dir = tempfile.mkdtemp()
121
 
122
+ # Use columns for sidebar-like layout
123
+ col_guide, col_main = st.columns([1, 2])
 
 
 
 
124
 
125
+ # LEFT SIDEBAR - GUIDE
126
+ with col_guide:
127
+ st.markdown("### πŸ“– How to Use This App")
128
+ with st.expander("**Click to Expand Guide**", expanded=True):
129
+ st.markdown("""
130
+ <div class="guide-box">
131
+ <h4>🎯 Quick Start Guide:</h4>
132
+
133
+ **Step 1: Choose Your Level** πŸ‘‡
134
+ - Select your age group
135
+ - 4-6: Basic counting
136
+ - 7-9: Addition, subtraction
137
+ - 13-15: Advanced math
138
+
139
+ **Step 2: Pick a Category** πŸ“š
140
+ - Choose math type to practice
141
+ - Each category has different questions
142
+
143
+ **Step 3: Solve Problems** ✏️
144
+ - Read each question
145
+ - Type your answer
146
+ - Click "Submit Answer"
147
+
148
+ **Step 4: Get Help** πŸ’‘
149
+ - Use "Show Hint" if stuck
150
+ - "Show Steps" for explanation
151
+ - "Skip" for next question
152
+
153
+ **Tips:** 🌟
154
+ - Take your time
155
+ - Mistakes help you learn!
156
+ - Practice regularly
157
+ </div>
158
+ """, unsafe_allow_html=True)
159
+
160
+ # Age group setup
161
+ age_groups = {
162
+ "4-6 Age Group": {"dataset": "src/Datase_of_4-6_Age_Group.xlsx", "zip_file": "src/Image_for_group_4-6.zip", "image_folder": "Image_for_group_4-6"},
163
+ "7-9 Age Group": {"dataset": "src/Datase_of_7-9_Age_Group.xlsx", "zip_file": "src/Image_for_group_7-9.zip", "image_folder": "Image_for_group_7-9"},
164
+ "13-15 Age Group": {"dataset": "src/Datase_of_13-15_Age_Group.xlsx", "zip_file": "src/Image_for_group_13-15.zip", "image_folder": "Image_for_group_13-15"},
165
+ }
166
 
167
+ # Age group selection in sidebar
168
+ st.markdown("---")
169
+ st.markdown("### πŸ§’ Choose Your Level")
170
+ selected_age_group = st.selectbox(
171
+ "Select age group:",
172
+ list(age_groups.keys()),
173
+ key="age_group_selector"
174
+ )
175
 
176
+ # Age group descriptions
177
+ age_descriptions = {
178
+ "4-6 Age Group": "🎨 **Fun with Numbers**: Counting, shapes, basic addition",
179
+ "7-9 Age Group": "πŸš€ **Math Adventures**: Addition, subtraction, multiplication",
180
+ "13-15 Age Group": "🌟 **Math Master**: Algebra, geometry, problem solving"
181
+ }
182
 
183
+ st.info(age_descriptions[selected_age_group])
 
 
 
 
 
 
 
184
 
185
+ # MAIN CONTENT AREA - RIGHT SIDE
186
+ with col_main:
187
+ # Welcome title
188
+ st.markdown("<div class='fun-title'>🧠✨ Welcome to the Smart Math Teacher! ✨🧠</div>", unsafe_allow_html=True)
 
189
 
190
+ # Initialize session
191
+ if "session_initialized" not in st.session_state or st.session_state.age_group != selected_age_group:
192
+ st.session_state.age_group = selected_age_group
193
+ st.session_state.category = None
194
+ st.session_state.question_index = 0
195
+ st.session_state.show_answer = False
196
+ st.session_state.show_steps = False
197
+ st.session_state.session_initialized = True
198
 
199
+ # Load dataset
200
+ group_info = age_groups[selected_age_group]
201
+ dataset_path = group_info["dataset"]
202
+ zip_path = group_info["zip_file"]
203
+ image_folder = group_info["image_folder"]
 
 
204
 
205
+ # Create image folder in temp directory
206
+ temp_image_folder = os.path.join(st.session_state.temp_dir, image_folder)
207
+ os.makedirs(temp_image_folder, exist_ok=True)
208
 
209
+ # Extract images if zip exists
210
+ try:
211
+ if os.path.exists(zip_path):
212
+ with zipfile.ZipFile(zip_path, "r") as zip_ref:
213
+ zip_ref.extractall(temp_image_folder)
214
+ except Exception as e:
215
+ st.warning(f"Error extracting images: {e}")
216
 
217
+ if not os.path.exists(dataset_path):
218
+ st.error(f"Dataset not found: {dataset_path}")
219
+ st.stop()
 
 
 
 
 
 
220
 
221
+ try:
222
+ df = pd.read_excel(dataset_path)
223
+ df['category'] = df['category'].astype(str).str.strip()
224
+ except Exception as e:
225
+ st.error(f"Error loading dataset: {e}")
226
+ st.stop()
 
227
 
228
+ # Category selection in main area
229
+ st.markdown("### πŸ“š Choose Your Math Category")
230
+ categories = sorted(df['category'].dropna().unique())
231
+ selected_category = st.selectbox(
232
+ "Select a category to practice:",
233
+ options=categories,
234
+ key="category_selector"
235
+ )
236
 
237
+ # Update session if category changes
238
+ if st.session_state.category != selected_category:
239
+ st.session_state.category = selected_category
240
+ st.session_state.question_index = 0
241
+ st.session_state.show_answer = False
242
+ st.session_state.show_steps = False
243
+ st.rerun()
244
 
245
+ # Filter questions by selected category only
246
+ subset_df = df[df['category'] == selected_category].reset_index(drop=True)
 
 
 
 
 
 
 
 
247
 
248
+ # MAIN CONTENT AREA - QUESTIONS
249
+ st.markdown("---")
250
 
251
+ if not subset_df.empty and st.session_state.question_index < len(subset_df):
252
+ question = subset_df.iloc[st.session_state.question_index]
253
+ progress = int((st.session_state.question_index / len(subset_df)) * 100)
254
+
255
+ # Progress information
256
+ col_progress1, col_progress2 = st.columns([3, 1])
257
+ with col_progress1:
258
+ st.progress(progress)
259
+ with col_progress2:
260
+ st.write(f"**{st.session_state.question_index + 1} of {len(subset_df)}**")
 
 
 
 
 
261
 
262
+ st.markdown(f"<div class='question-box'>πŸ“˜ <b>Question {st.session_state.question_index + 1}:</b><br><br>{question['problem']}</div>", unsafe_allow_html=True)
 
 
263
 
264
+ # Display image with error handling
265
+ if pd.notna(question.get('image')):
266
+ image_name = str(question['image']).strip()
267
+ image_found = False
268
+ for root, _, files in os.walk(temp_image_folder):
269
+ for file in files:
270
+ if file.lower().startswith(image_name.lower()) or os.path.splitext(file)[0].lower() == image_name.lower():
271
+ try:
272
+ st.image(Image.open(os.path.join(root, file)), use_column_width=True)
273
+ image_found = True
274
+ break
275
+ except:
276
+ pass
277
+ if not image_found:
278
+ st.warning("❌ Image not found for this question.")
279
+
280
+ # Answer section
281
+ st.markdown("### ✏️ Your Turn to Solve!")
282
+ user_ans = st.text_input("Type your answer below:", key=f"ans_{st.session_state.question_index}")
283
+
284
+ # Action buttons in columns
285
+ col1, col2, col3 = st.columns(3)
286
+
287
+ with col1:
288
+ if st.button("βœ… Submit Answer", use_container_width=True):
289
+ if str(user_ans).strip().lower() == str(question['answer']).strip().lower():
290
+ st.success("πŸŽ‰ Correct! Well done!")
291
+ st.balloons()
292
+ time.sleep(2)
293
+ st.session_state.question_index += 1
294
+ st.session_state.show_answer = False
295
+ st.session_state.show_steps = False
296
+ st.rerun()
297
+ else:
298
+ st.error("❌ Not quite right. Try again or use the hint below!")
299
+ st.session_state.show_answer = True
300
+ st.session_state.show_steps = False
301
+
302
+ with col2:
303
+ if st.button("πŸ’‘ Show Hint", use_container_width=True):
304
+ st.session_state.show_answer = True
305
+ st.session_state.show_steps = False
306
+ st.info("πŸ’‘ Need help? Check the answer below!")
307
+
308
+ with col3:
309
+ if st.button("⏭️ Skip Question", use_container_width=True):
310
  st.session_state.question_index += 1
311
  st.session_state.show_answer = False
312
  st.session_state.show_steps = False
313
  st.rerun()
 
 
 
 
314
 
315
+ # Help sections
316
+ if st.session_state.show_answer:
317
+ st.markdown("---")
318
+ st.markdown("### πŸ’‘ Need Help?")
319
+ st.info(f"**βœ… Correct Answer:** **{question['answer']}**")
320
+
321
+ if selected_age_group in ["7-9 Age Group", "13-15 Age Group"]:
322
+ if st.button("πŸ” Show Step-by-Step Solution"):
323
+ st.session_state.show_steps = True
324
+
325
+ if st.session_state.show_steps and pd.notna(question.get("steps", None)):
326
+ st.success(f"### πŸͺ„ How to Solve:\n{question['steps']}")
327
 
328
+ elif subset_df.empty:
329
+ st.warning("⚠️ No questions available in this category. Please try another category!")
330
+ else:
 
 
 
 
 
 
331
  st.markdown("---")
332
+ st.success("""
333
+ # πŸ† Congratulations!
334
 
335
+ ### You've completed all questions in this category!
 
 
336
 
337
+ πŸŽ‰ **Great job!** You're becoming a math superstar!
338
+
339
+ **What to do next:**
340
+ - Try another category in the same age group
341
+ - Move to a more challenging age group
342
+ - Practice regularly to keep improving!
343
+ """)
344
+ st.balloons()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
 
346
  # Cleanup function
347
  def cleanup():