NSamson1 commited on
Commit
ba6e291
·
verified ·
1 Parent(s): 35cab13

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +78 -14
src/streamlit_app.py CHANGED
@@ -8,6 +8,9 @@ import sympy as sp
8
  import time
9
  from sentence_transformers import SentenceTransformer
10
  from sklearn.metrics.pairwise import cosine_similarity
 
 
 
11
 
12
  # Page config
13
  st.set_page_config(page_title="🎓 Smart Math Teacher", layout="centered")
@@ -25,6 +28,10 @@ st.markdown("""
25
  # Welcome title
26
  st.markdown("<div class='fun-title'>🧠✨ Welcome to the Smart Math Teacher! ✨🧠</div>", unsafe_allow_html=True)
27
 
 
 
 
 
28
  # Age group setup
29
  age_groups = {
30
  "4-6 Age Group": {"dataset": "Dataset%20for%204-6%20Age%20Group.xlsx", "zip_file": "Image_for_group_4-6.zip", "image_folder": "Image_for_group_4-6"},
@@ -49,18 +56,33 @@ dataset_path = group_info["dataset"]
49
  zip_path = group_info["zip_file"]
50
  image_folder = group_info["image_folder"]
51
 
52
- os.makedirs(image_folder, exist_ok=True)
53
- if not any(f.lower().endswith(('.png', '.jpg', '.jpeg')) for f in os.listdir(image_folder)):
 
 
 
 
54
  if os.path.exists(zip_path):
55
  with zipfile.ZipFile(zip_path, "r") as zip_ref:
56
- zip_ref.extractall(image_folder)
 
 
 
 
 
 
 
57
 
58
  if not os.path.exists(dataset_path):
59
  st.error(f"Dataset not found: {dataset_path}")
60
  st.stop()
61
 
62
- df = pd.read_excel(dataset_path)
63
- df['category'] = df['category'].astype(str).str.strip()
 
 
 
 
64
 
65
  # Category selection
66
  categories = sorted(df['category'].dropna().unique())
@@ -84,17 +106,37 @@ if not subset_df.empty and st.session_state.question_index < len(subset_df):
84
 
85
  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)
86
 
87
- # Display image
88
  if pd.notna(question.get('image')):
89
  image_name = str(question['image']).strip()
90
- for root, _, files in os.walk(image_folder):
 
 
 
91
  for file in files:
92
  if file.lower().startswith(image_name.lower()) or os.path.splitext(file)[0].lower() == image_name.lower():
93
  try:
94
- st.image(Image.open(os.path.join(root, file)), use_column_width=True)
95
- except:
96
- st.warning("❌ Image couldn't be loaded.")
97
- break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
  user_ans = st.text_input("📝 Your Answer:", key=f"ans_{st.session_state.question_index}")
100
 
@@ -140,7 +182,8 @@ def load_model():
140
 
141
  model = load_model()
142
 
143
- qa_pairs = {
 
144
  "what is the area of a triangle": "Area = (1/2) × base × height",
145
  "what is the area of a square": "Area = side²",
146
  "what is the area of a circle": "Area = π × radius²",
@@ -153,7 +196,18 @@ qa_pairs = {
153
  "what is the derivative of x squared": "The derivative of x² is 2x."
154
  }
155
 
156
- qa_questions = list(qa_pairs.keys())
 
 
 
 
 
 
 
 
 
 
 
157
  qa_embeddings = model.encode(qa_questions)
158
 
159
  st.markdown("## 💡 Ask Any Math Question")
@@ -166,7 +220,7 @@ if question_input:
166
  best_score = scores[best_idx]
167
 
168
  if best_score > 0.6:
169
- st.success(f"🤖 Answer:\n\n**{qa_pairs[qa_questions[best_idx]]}**")
170
  else:
171
  try:
172
  if "derivative" in question_input.lower():
@@ -180,3 +234,13 @@ if question_input:
180
  st.success(f"✅ Answer: {simplified}")
181
  except Exception as e:
182
  st.warning(f"⚠️ Couldn't understand the question. Error: {e}")
 
 
 
 
 
 
 
 
 
 
 
8
  import time
9
  from sentence_transformers import SentenceTransformer
10
  from sklearn.metrics.pairwise import cosine_similarity
11
+ import tempfile
12
+ import pickle
13
+ import pickletools
14
 
15
  # Page config
16
  st.set_page_config(page_title="🎓 Smart Math Teacher", layout="centered")
 
28
  # Welcome title
29
  st.markdown("<div class='fun-title'>🧠✨ Welcome to the Smart Math Teacher! ✨🧠</div>", unsafe_allow_html=True)
30
 
31
+ # Initialize session state for temp directory
32
+ if 'temp_dir' not in st.session_state:
33
+ st.session_state.temp_dir = tempfile.mkdtemp()
34
+
35
  # Age group setup
36
  age_groups = {
37
  "4-6 Age Group": {"dataset": "Dataset%20for%204-6%20Age%20Group.xlsx", "zip_file": "Image_for_group_4-6.zip", "image_folder": "Image_for_group_4-6"},
 
56
  zip_path = group_info["zip_file"]
57
  image_folder = group_info["image_folder"]
58
 
59
+ # Create image folder in temp directory
60
+ temp_image_folder = os.path.join(st.session_state.temp_dir, image_folder)
61
+ os.makedirs(temp_image_folder, exist_ok=True)
62
+
63
+ # Extract images if zip exists
64
+ try:
65
  if os.path.exists(zip_path):
66
  with zipfile.ZipFile(zip_path, "r") as zip_ref:
67
+ zip_ref.extractall(temp_image_folder)
68
+ else:
69
+ st.warning(f"Zip file not found: {zip_path}. Using default images if available.")
70
+ except PermissionError as e:
71
+ st.error(f"Permission error accessing files: {e}")
72
+ st.info("Using default images without extraction.")
73
+ except Exception as e:
74
+ st.error(f"Error extracting images: {e}")
75
 
76
  if not os.path.exists(dataset_path):
77
  st.error(f"Dataset not found: {dataset_path}")
78
  st.stop()
79
 
80
+ try:
81
+ df = pd.read_excel(dataset_path)
82
+ df['category'] = df['category'].astype(str).str.strip()
83
+ except Exception as e:
84
+ st.error(f"Error loading dataset: {e}")
85
+ st.stop()
86
 
87
  # Category selection
88
  categories = sorted(df['category'].dropna().unique())
 
106
 
107
  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)
108
 
109
+ # Display image with error handling
110
  if pd.notna(question.get('image')):
111
  image_name = str(question['image']).strip()
112
+ image_found = False
113
+
114
+ # Check in temp directory first
115
+ for root, _, files in os.walk(temp_image_folder):
116
  for file in files:
117
  if file.lower().startswith(image_name.lower()) or os.path.splitext(file)[0].lower() == image_name.lower():
118
  try:
119
+ img_path = os.path.join(root, file)
120
+ st.image(Image.open(img_path), use_column_width=True)
121
+ image_found = True
122
+ break
123
+ except Exception as e:
124
+ st.warning(f"❌ Couldn't load image: {e}")
125
+
126
+ if not image_found:
127
+ # Fallback to original image folder
128
+ for root, _, files in os.walk(image_folder):
129
+ for file in files:
130
+ if file.lower().startswith(image_name.lower()) or os.path.splitext(file)[0].lower() == image_name.lower():
131
+ try:
132
+ st.image(Image.open(os.path.join(root, file)), use_column_width=True)
133
+ image_found = True
134
+ break
135
+ except Exception as e:
136
+ st.warning(f"❌ Couldn't load image: {e}")
137
+
138
+ if not image_found:
139
+ st.warning("❌ Image not found.")
140
 
141
  user_ans = st.text_input("📝 Your Answer:", key=f"ans_{st.session_state.question_index}")
142
 
 
182
 
183
  model = load_model()
184
 
185
+ # Use pickle to store and share QA data efficiently
186
+ qa_data = {
187
  "what is the area of a triangle": "Area = (1/2) × base × height",
188
  "what is the area of a square": "Area = side²",
189
  "what is the area of a circle": "Area = π × radius²",
 
196
  "what is the derivative of x squared": "The derivative of x² is 2x."
197
  }
198
 
199
+ # Store QA data using pickle (for demonstration)
200
+ try:
201
+ with open('qa_data.pkl', 'wb') as f:
202
+ pickle.dump(qa_data, f)
203
+
204
+ # Optional: disassemble and analyze pickle (for debugging)
205
+ with open('qa_data.pkl', 'rb') as f:
206
+ pickletools.dis(f)
207
+ except Exception as e:
208
+ st.warning(f"Could not create pickle file: {e}")
209
+
210
+ qa_questions = list(qa_data.keys())
211
  qa_embeddings = model.encode(qa_questions)
212
 
213
  st.markdown("## 💡 Ask Any Math Question")
 
220
  best_score = scores[best_idx]
221
 
222
  if best_score > 0.6:
223
+ st.success(f"🤖 Answer:\n\n**{qa_data[qa_questions[best_idx]]}**")
224
  else:
225
  try:
226
  if "derivative" in question_input.lower():
 
234
  st.success(f"✅ Answer: {simplified}")
235
  except Exception as e:
236
  st.warning(f"⚠️ Couldn't understand the question. Error: {e}")
237
+
238
+ # Cleanup function (optional)
239
+ def cleanup():
240
+ import shutil
241
+ if 'temp_dir' in st.session_state and os.path.exists(st.session_state.temp_dir):
242
+ shutil.rmtree(st.session_state.temp_dir)
243
+
244
+ # Register cleanup when app closes
245
+ import atexit
246
+ atexit.register(cleanup)